Angular 4 将相同的指令应用于迭代中的所有 div



我在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 [名称]和app.url时,每个div都不同。控制台输出"Əlavə"3 次,这意味着角度指令不会动态更改 [name] 属性。

这是因为在您的支票中使用

if (this.name = 'Əlavə') {

这实际上会将名称设置为'Əlavə'- 您应该改用===(请参阅:=====之间的区别 (

if (this.name === 'Əlavə') {

但在这种情况下,您可能最好使用这样的 switch 语句

switch (this.name) {
case 'Əlavə': 
this.renderer.setStyle(this.elementRef.nativeElement, 'background-color', 'yellow');
break;
case 'LMS': 
this.renderer.setStyle(this.elementRef.nativeElement, 'background-color', 'red');
break;
case 'MHS': 
break;
this.renderer.setStyle(this.elementRef.nativeElement, 'background-color' , 'green');
break;
default:
this.renderer.setStyle(this.elementRef.nativeElement, 'background-color', 'blue');
}

这是一个解决问题的现场 plunker 演示

最新更新