Search code examples
javascriptangularangular2-changedetection

Angular2 - Detect Changes of Attribute @Input


I have a simple Attribute Directive mask, with an @Input() mask:string

I want to be able to detect and react to changes on the mask binding I can use ngOnChanges somehow, but I feel like this is like painting the problem with a large brush

Sample/Simplified code of directive:

@Directive({
  selector: 'mask'
})
export class MaskDirective implements AfterViewInit {
  @Input() mask: string;

  constructor(public el: ElementRef) {};

  ngAfterViewInit() {
    $(this.el.nativeElement).mask(this.mask);
  }
}

Usage:

<input type='text' [mask]='someBinding'>

When the value of someBinding changes, how to execute some code, without relying on ngChanges ?


Solution

  • You can use setter method for mask property instead of more broad ngOnChanges:

    @Directive({
      selector: 'mask'
    })
    export class MaskDirective implements AfterViewInit {
      @Input set mask(newValue: string) {
        $(this.el.nativeElement).mask(newValue);
      }
    
      constructor(public el: ElementRef) {};
    
    
    }
    

    Setter is going to be more efficient as it's related to only this property.