1
votes

I am building an attribute directive, which changes the background color of the host element accounting to a "quality" @input.

I found that if I implement ngOnChanges as a lambda expression, the ngOnchanges method would not be invoked when input changes.

My playground:

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() {

  }


}
1
Not an answer, but you could make the code simpler by using a getter for the backgroundColor, or a setter for your input. - JB Nizet

1 Answers

4
votes

this behaviour has issue on github.

As described in #7270 (comment) this is by design. Doing this would make the runtime slower and it would prevent tree shaking. so we are not going to implement this.

Stated by mhevery member of angular team