【发布时间】:2018-01-01 08:45:47
【问题描述】:
我在 Angular 中遇到了奇怪的行为。我想根据来自数据库的信息呈现div 和样式。
模板
<div *ngFor="let app of apps" >
<div appApplicationColor [name]="app.name.az">
<a href="{{app.url}}?token={{token}}" target="_blank">
<p>{{app.name.az}} </p>
</a>
</div>
</div>
App.name.az 是 ="Əlavə", 'LMS' , 'MHS' 并且 appApplicationColor 指令是
组件
@Directive({
selector: '[appApplicationColor]'
})
export class ApplicationColorDirective implements OnInit, OnDestroy {
@Input() name: string;
constructor(private elementRef: ElementRef , private renderer: Renderer2)
{
}
ngOnInit() {
if (this.name = 'Əlavə') {
this.renderer.setStyle(this.elementRef.nativeElement, 'background-color', 'yellow');
} else if (this.name = 'LMS') {
this.renderer.setStyle(this.elementRef.nativeElement, 'background-color', 'red');
} else if (this.name = 'MHS') {
this.renderer.setStyle(this.elementRef.nativeElement, 'background-color' , 'green');
} else {
this.renderer.setStyle(this.elementRef.nativeElement, 'background-color', 'blue');
}
console.log(this.name)
}
}
问题是所有 div 都变成黄色,而不是根据它们的app.name.az。奇怪的是,当我检查 div [name] 和 app.url 时,它们各自不同。控制台输出 'Əlavə' 3 次,这意味着 angular 指令不会动态更改 [name] 属性。
【问题讨论】:
-
这很奇怪——我遇到了和你一样的问题,但是当我调整它时——它已经解决了。现在我看不出我的代码和你的代码有什么区别。 Here is the plunker example如果你能发现它!
-
啊!我找到了!
标签: angular angular2-directives angular-directive