【问题标题】:Angular 4 applies same directive to all divs within iterationAngular 4 对迭代中的所有 div 应用相同的指令
【发布时间】: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


【解决方案1】:

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

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

【讨论】:

  • 它就像一个魅力!我什至没有意识到问题可能是因为这个。你是救生员))非常感谢。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-10-21
  • 1970-01-01
  • 2019-01-16
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多