<google-signin
height = ""
width = ""
theme = ""
signedIn= ""
brand = ""
needAdditionalAuth = "" class = "{{_class}}">
</google-signin>
在指令中 -
ngOnInit(){
this._class = "height-" + this._height + " width-" + this._width + " theme-" + this._theme + " signedIn-" + this._signedIn + " brand-" + this._brand + " additionalAuth-" + this._needAdditionalAuth;
}
我想根据提供的属性值计算googleSignin元素的类。然后,这个计算出的类字符串将引用css文件中定义的几个类。
我该怎么做?
答案 0 :(得分:1)
您可以利用组件中的Renderer
类。后者需要为每个属性定义输入,并根据ngOnChanges
方法对更新做出反应:
@Input('height') {
_height: string;
(...)
constructor(private renderer:Renderer, private elt:ElementRef) {
}
ngOnChanges(){
// Remove the previous class if any for "height"
if (this.previousHeightClass) {
this.renderer.setElementClass(this.elt.nativeElement,
this.previousHeightClass, false);
}
// Add the new class for "height"
this.renderer.setElementClass(this.elt.nativeElement,
'height-' + this._height, true);
(...)
// Save the previous class for "height
this.previousHeightClass = "height-" + this._height;
}
您可以这样使用您的组件:
<google-signin
[height] = "height"
(...)
[needAdditionalAuth] = "needAdditionalAuth">
</google-signin>
您可以使用输入进行更新height
:
<google-signin
[height] = "height">
</google-signin>
<input [(ngModel)]="height" value="test"/>
相应地添加/删除课程......
请参阅此plunkr:https://plnkr.co/edit/jOlEWZzilTId3gruhu9B?p=preview。
答案 1 :(得分:1)
只需使用[ngClass]="_class"
<google-signin
height = ""
width = ""
theme = ""
signedIn= ""
brand = ""
needAdditionalAuth = "" [ngClass]="_class">
</google-signin>
Plunker example
如果您调查DOM,您会看到class="yyy"
已添加。