2

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
  • 31
  • 1
  • 4
  • 1
    Possible duplicate of [How to detect when an @Input() value changes in Angular?](https://stackoverflow.com/questions/38571812/how-to-detect-when-an-input-value-changes-in-angular) – abney317 May 17 '19 at 15:49
  • https://angular.io/guide/component-interaction#intercept-input-property-changes-with-ngonchanges – Alexander Staroselsky May 17 '19 at 15:49

2 Answers2

7

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
  • 655
  • 3
  • 11
4

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
  • 56
  • 7