3

I need to detect value changes in @Input binding angular and execute a function when the value is changed

@Component({
  selector: 'my-comp',
  ...
})
...
@Input() myValue

//detect myValue changes

<my-comp [myValue]= "val"></my-comp>

I need to execute some code component class when val changes.

san gallage
  • 41
  • 1
  • 4

2 Answers2

9

You could simply use set here, like this:

_myvalue: any;
@Input() set myValue(value: any) {
    ... // Your code goes here
    this._myvalue = value;
}

Now, everytime you assign a value to myValue inside your template the setter is called and your code will be executed.

I hope that helps!

nullchimp
  • 735
  • 4
  • 13
5

You can use ngOnChange lifecycle hook in angular for advance features.

export class MyCoponent implements OnChanges{

@Input() myValue

ngOnChanges(changes:SimpleChange){

 //current value
 let currentVal= changes.myValue.currentValue
 // previouse value
 let prev = changes.previousValue
}

ngOnChanges function execute when any changes in myValue

Sigma Dev
  • 66
  • 7