【问题标题】:Angular 6, directive ngOnChanges does not work with a lambda expression?Angular 6,指令 ngOnChanges 不适用于 lambda 表达式?
【发布时间】:2026-01-28 20:20:06
【问题描述】:

我正在构建一个属性指令,它将宿主元素的背景颜色更改为“质量”@input。

我发现如果我将 ngOnChanges 实现为 lambda 表达式,那么当输入更改时不会调用 ngOnchanges 方法。

我的游乐场:

https://stackblitz.com/edit/angular-6-playground-lqwps2?file=src%2Fapp%2FmyOrder.directive.ts

@Directive({
  selector: '[my-order]'
})

export class MyOrderDirective {

  @Input()
  quality: number = 1;

  @HostBinding('style.background-color')
  backgroundColor: string;


  // ************* works ********************
  // ngOnChanges(changes: SimpleChanges) {
  //   if (this.quality % 2 == 0) {
  //     this.backgroundColor = 'red';
  //
  //   } else {
  //     this.backgroundColor = 'blue';
  //   }
  //
  // };


  // ******* lambda expression does NOT work ***********
  ngOnChanges = (changes: SimpleChanges) => {
    if (this.quality % 2 == 0) {
      this.backgroundColor = 'red';

    } else {
      this.backgroundColor = 'blue';
    }

  };

  // ******************** Not work *********************
  // ngOnChanges = function (changes: SimpleChanges) {
  //   if (this.quality % 2 == 0) {
  //     this.backgroundColor = 'red';
  //
  //   } else {
  //     this.backgroundColor = 'blue';
  //   }
  //
  // };


  constructor() {

  }


}

【问题讨论】:

  • 不是答案,但您可以通过使用背景颜色的 getter 或输入的 setter 来简化代码。

标签: angular typescript


【解决方案1】:

此行为存在问题on github

#7270(评论)中所述,这是设计使然。这样做会使运行时变慢,并且会防止摇晃树。所以我们不打算实现它。

mhevery Angular 团队成员声明

【讨论】: