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

Angular 4 applies same directive to all divs within iteration

我在 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] 属性。

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

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

这实际上 名称设置为 'Əlavə' - 您应该改为使用 ===(参见:Difference between == and ===

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

但在这种情况下,您最好使用这样的 switch statement

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');
}

Here is a live plunker demo fixing the problem