2016-11-11 24 views
0

我想基于来自@input的属性有条件地将一个类应用于div,但是当相同条件针对不是@input属性(如下面的test_active)表达式正常工作。基于@input无法在Angular2中评估ngClass

我可以console.log()init()函数中的属性值,我确实得到了正确的值。

这里是我的组件

import {Component, OnInit, Input} from '@angular/core'; 

@Component({ 
    selector: 'app-avatar', 
    template: ` 
    <div 
     id="avatar" 
     [ngClass]="{'active': active?true:false, 'inactive': active?false:true}" 
    ></div> 
    `, 
    styles: [ 
... 
    `#avatar.active { border-color: #77ED00;}`, 
    `#avatar.inactive {filter: grayscale(100%); border-color: red}` 
    ] 
}) 
export class AvatarComponent implements OnInit { 

    @Input() active; 

    test_active = true; 


    constructor() { } 

    ngOnInit() { 
    console.log(this.active); //true 
} 


} 
+0

这里可以正常工作:https://plnkr.co/edit/6hOyjh0PlXRr20i49xJ3?p=preview。在plunkr中发布相关代码以重现问题。 –

回答

1

的示例代码我假定你传递的值作为字符串输入。

尝试

<app-avatar [active]="true"></app-avatar> 
<app-avatar [active]="false"></app-avatar> 
1

重要的您列出没有在他们的边界border-style: dashed固体,或任何一种风格的CSS类,以便他们做出渲染不是追加类名的DOM其他零差价。虽然输入肯定是正确应用。

我也建议你做[ngClass]="{'active': active, 'inactive: !active}"为自己节省一些不必要的三元组。