如何为Angular2中元素的类属性赋值

时间:2016-04-04 09:30:06

标签: angularjs angular

<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文件中定义的几个类。

我该怎么做?

2 个答案:

答案 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"已添加。