Currently, I am in the process of creating an attribute directive that is designed to alter the background color of the host element based on a provided "quality" @input.
While experimenting with my directive, I discovered that using ngOnChanges as a lambda expression prevented the ngOnchanges method from being called when the input value changed.
Here is a link to my playground where you can see the code in action:
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() {
}
}