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.

1

2 Answers 2

10

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!

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.