2

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 ?

1 Answer 1

4

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.

Sign up to request clarification or add additional context in comments.

2 Comments

Thanks for your reply; It'd be great if it'd work but then I get a duplicate identifier 'mask' error. Did you actually managed to do this so it works or? Ideas?
Never mind that - Your solution works, except you need to decorate the setter itself with the @Input decorator I sent an edit with the fix Thanks!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.