【发布时间】: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