Angular @input Check Which Property Changed using OnChanges

Using @Input decorator parent component can pass values to child components using property binding. But there may be a case where we are passing more than one property in a child component.

We may need control on which property is changed and also check if other properties have changed from the previous one or not.

In this tutorial, we will discuss how to check which of the passed input properties changed by using the OnChanges lifecycle hook of a component.

Here we have a parent component with two buttons to add scores of two teams. The child component TeamScoresComponent will display the updated latest scores with all progress of the match.

Child Component

In the terminal window run following command to create a child component TeamScoresComponent

In the team-scores.component.html file place following HTML template

The matchProgress will keep the progress of match as an array. The teamA and teamB variables will show updated scores.

In the team-scores.component.ts class file place following code

The ngOnChanges method is called on child component load and whenever a value is passed via Input properties which are teamA and teamB here.

Using the SimpleChange class type we can fetch the properties which are changed and also the value of the previous and current instance.

Parent Component

Now we will add the app-team-scores component in App component with teamA and teamB input properties.

There are two buttons to update the scores of each team.

In the app.component.html file add following code

In app.component.ts class, file add following code


Leave a Reply

Notify of