ngOnChanges Life Cycle Hook In Angular2
Posted By : Prashank Jauhari | 30-Nov-2017
ngOnChanges Life cycle hook in angular2
Prerequisite:
1)Component interaction using @Input() and @Output() Properties.
Parent and child component in angular2 communicate with each other using there @input's and @output's databound properties.Sometime during there life cycle we need a way to get a handle
when there values changes, for this purpose angular 2 provides ngOnChnages() life cycle hook inside @angular/core package. Below snapshot provides a sample code to demonstrate on how to use ngOnChange life cycle hook.
I will be using same code from my previous blog entitled “Creating form in in angular 2 using json schema at run time”.
Step 1)Create an sample @Input property in SignupComponent.
Step 2)Inside the parent component.html bind this input property to some vairable inside parent's component.ts file.
Note: Consider @Input property like a tunnel which is used to pass data from parent to child and vica versa for @Output property.
Template of parent component(app.component.html)
Explanation: Inside app.component.html i bind the @input property of child to parent's parentToChild field. Whenever i click on Toggle button @Input property change which in turn fire the ngOnChange life cycle hook of child component(SignUpComponent).
parentToChild literal of type boolean and toggle function inside parent's component.ts file (app.component.ts file)
Step 3)
Inside child component.ts file implement onChange interface from @angular/core and provide the implementation of ngOnChange
Inside ngOnChange angular2 provide us simpleChanges object which let use iterate through @Input and @Output property and get the current and previous value of property.
For More Information about ngOnChange life cycle hook go through the following link.
Cookies are important to the proper functioning of a site. To improve your experience, we use cookies to remember log-in details and provide secure log-in, collect statistics to optimize site functionality, and deliver content tailored to your interests. Click Agree and Proceed to accept cookies and go directly to the site or click on View Cookie Settings to see detailed descriptions of the types of cookies and choose whether to accept certain cookies while on the site.
About Author
Prashank Jauhari
Prashank is quick learner and passionate about new technologies. He is currently working as Java Developer with knowledge of Spring and Hibernate.