我知道,在我Angular2可以通过这样一类“红色”添加到组件的选择元素:
@Component({
selector: 'selector-el',
host: {
'[class.red]': 'true'
},
...
})
我不知道是否有一个动态类添加到主机,类似于您用NgClass做什么(我知道NgClass实际上不支持,我在寻找可能的解决方案)的方式:
@Component({
selector: 'selector-el',
host: {
'[NgClass]': 'colorClass'
},
...
})
...
constructor(){
this.colorClass = 'red';
}
您可以使用类似的东西:
@Directive({
(...)
host: {
'[class.className]' : 'className',
'[class]' : 'classNames'
}
}
export class MyDirective {
constructor() {
this.className = true;
this.classNames = 'class1 class2 class3';
}
}
所述Renderer
s setElementClass
可用于添加或删除的任意类。对于其中md-[color]
由输入提供示例color
<some-cmp [color]="red">
@Component({
// @Directive({
selector: 'some-cmp',
template: '...'
})
export class SomeComp {
_color: string;
@Input()
set color(color: string) {
this._color = color;
this.renderer.setElementClass(this.elementRef.nativeElement, 'md-' + this._color, true);
}
get color(): string {
return this._color;
}
constructor(private elementRef: ElementRef, private renderer: Renderer){}
}
如果你喜欢它从外面可以结合@HostBinding
和@Input()
改变:
@Component({
selector: 'my-component',
template: ``
})
export class MyComponent {
@HostBinding('class.your-class') @Input() isSelected: boolean;
}
import {Component, HostBinding} from 'angular2/core';
@Component({
(...)
}
export class MyComponent {
@HostBinding('class') colorClass = 'red';
}
我最近做了一个指令称为<ng-host>
(由this issue启发),它会重定向到组件主机元素,使用每个(非结构性)的变化:
@Component({
template: `
<ng-host [ngClass]="{foo: true, bar: false}"></ng-host>
<p>Hello World!</p>
`
})
class AppComponent { }
在线演示可以发现here。
支持的用途定义here。
我已经通过指令来实现此作为服务模式,即手动提供NgClass
和使用它像(online demo)
由于DI机制,NgClass
将获得当前主机元素的ElementRef
的Self()
修改有助于保证。因此,没有必要通过构造下的公共API使用创建一个实例,因此仍然。
这可能是在与类继承相结合更简洁,一个例子可以在here找到。
你可以做到以下几点:
import {Component} from "@angular/core"
@Component({
selector: "[textbox]",
host: {"class": "first-class secondClass ThirdClass AnYClaSs"},
template: ...
})
export class MyComponent { }
这是海事组织比采用可变的方式更直接。 应Angular2 RC5,RC6,RC7,最后的工作。在早期版本可以工作,但没有尝试它。