Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Detect when input value changed in directive

I'm trying to detect when the value of an input changed in a directive. I have the following directive:

    import { ElementRef, Directive, Renderer} from '@angular/core';      @Directive({         selector: '[number]',         host: {"(input)": 'onInputChange($event)'}     })      export class Number {          constructor(private element: ElementRef, private renderer: Renderer){          }         onInputChange(event){             console.log('test');         }     } 

The problem in this directive is that it detects only when there is an input and not when the value changes programatically. I use reacive form and sometimes I set the value with the patchValue() function. How can I do so the change function gets triggered?

like image 319
ncohen Avatar asked Jan 18 '17 19:01

ncohen


1 Answers

You need to make an input property of input and then use the ngOnChanges hook to tell when the input property changes.

@Directive({     selector: '[number]' }) export class NumberDirective implements OnChanges {     @Input() public number: any;     @Input() public input: any;      ngOnChanges(changes: SimpleChanges){       if(changes.input){         console.log('input changed');       }     } } 

Plunkr

Stackblitz

like image 194
Teddy Sterne Avatar answered Sep 18 '22 14:09

Teddy Sterne