Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular2 Call Function When the Input Changes

Child component:

export class Child {     @Input() public value: string;     public childFunction(){...} } 

Parent component:

export class Parent {     public value2: string;     function1(){ value2 = "a" }     function2(){ value2 = "b" } } 

Parent view:

<child [value]="value2"> 

Is there any way to call childFunction() every time the value2 is changed in this structure?

like image 668
Bünyamin Sarıgül Avatar asked Sep 05 '16 12:09

Bünyamin Sarıgül


People also ask

What is input event in angular?

The "input" event, unlike the "change" event, is a synchronous event that is triggered as the user is interacting with the text-based input controls.

Can we call function in angular?

Calling a function or initializing a single value on page load in AngularJS is quite easy. AngularJS provides us with a dedicated directive for this specific task. It's the ng-init directive. Example 1: In this example, we will call a function to initialize a variable on page load.


1 Answers

You can use the ngOnChanges() lifecycle hook

export class Child {     @Input() public value: string;      ngOnChanges(changes) {       this.childFunction()     }     public childFunction(){...} } 

or use a setter

export class Child {     @Input()      public set value(val: string) {       this._value = val;       this.childFunction();     }     public childFunction(){...} } 
like image 61
Günter Zöchbauer Avatar answered Oct 10 '22 15:10

Günter Zöchbauer