Detecting @Input property changes in Angular

0

In the article Parent-Child Component Interaction in Angular 11, we learned how to pass data to a child component using the tool @Contribution decorator. It is not only easy to use, but automatically handles updates for us so that model variables are updated immediately every time a @Contribution the value of the variable changes. But what if we have to change a @Contribution variable before referencing it in the model? If only there was an event that would trigger every time a @Contribution the value of the variable has changed. It turns out yes! it’s called ngOnChanges () event, and by the end of this tutorial, you will know exactly how it works and how to use it.

ngOnChanges () Prime in angular

ngOnChanges () is just one of many hooks in the Angular lifecycle. Others include, ngOnInit (), ngAfterViewInit (), and ngOnDestroy (). the ngOnChanges () method is invoked before ngOnInit (), as well as whenever Angular defines a @Contribution property, which makes it ideal for responding to changes in a @Contribution variable. Changes can occur for a number of different reasons such as user interaction, asynchronous invocation, etc.

the ngOnChanges () The method accepts one argument: a Simple Change object that is mapped to each changed property. It defines three properties as follows:

SimpleChange {
  previousValue: any;
  currentValue: any;
  firstChange: boolean;
}

The first two properties contain the current and previous property values ​​respectively, while the firstedit tells us if this was the first time the change has taken place.

Working with the ngOnChanges () method

We can tell the compiler that we want to respond to changes in the @Input variable by implementing the OnChanges interface. From there we can ask VS Code to generate the ngOnChanges () method by hovering the cursor over the class name and clicking the quick fix icon when it appears. This will bring up a suggestion to “Implement the “OnChanges” interface “:

This will place the method just below the component name. I like to move it a bit lower, somewhere after the variables in component scope, but it doesn’t have to be.

Mapping SimpleChange Objects

Now we need a @Contribution variable to respond to. I happen to have one right here. Remember the query variable from last week’s demo? It is updated every time the user clicks on the Add button, so we should be able to intercept them in the ngOnChanges () method. Indeed, here is:

Mapping SimpleChange objects in Angular

Currently no property mapping is done because we only have one @Contribution variable. To see what’s going on with multiple variables, let’s add a Shipping Address field. Now we can see that each Simple Change is mapped to a property whose name matches that of the variable it follows:

SimpeChange with multiple arams

Build a list of requests

The original Order the page only accepted one special request at a time. Let’s modify it so that additional queries are added to a list rather than replacing the previous one.

In the child.component file, we will convert the requests variable in the singular to indicate that these are individual requests. The complete list of requests will now be stored in the plural requests variable:

@Input() request: string = '';
public requests: Array = [];

In the ngOnChanges () method, we will:

  1. make sure there are new requests
  2. check that the value is not an empty string
  3. add the last request at requests deploy

here is ngOnChanges () code that performs the three actions above:

ngOnChanges(changes: SimpleChanges): void {
  // check if there are requests
  const latestRequest = changes['request'];
  if (latestRequest) {
    // don't accept empty values
    // the first one will be empty as well, since the default value 
    // gets passed in when the child component is created.
    if ((latestRequest.currentValue as string).trim() !== '') {
      this.requests.push(latestRequest.currentValue);
    }
  }
}

the current value property (as well as previous value) has a type of any because the Simple modifications the object has no way of knowing in advance what type it will store. Therefore, in order to treat the query as a string, we can convert it using the code (latestRequest.currentValue as string). This will tell the IDE which methods to display in the autocomplete list, allowing us to select the trim () method:

Casting in JavaScript and Angular

In addition to avoiding empty values, checking for empty strings also avoids listing the default request value of “due to ngOnChanges () pull forward ngOnInit (). We could also check the firstedit attribute, but checking for an empty string works just as well for our purposes.

We’ll also update the template to show requests as an unordered list:

Special requests

None
  • {{request}}

The demo

Here’s a screenshot that shows the updated demo, with the new list of delivery addresses and special requests:

Angular example

Conclusion

In this tutorial, we have learned how to answer @Contribution changes in variables by implementing the OnChanges interface. One of the many angular lifecycle hooks, the ngOnChanges () method allows us to easily manage all @Contribution variable updates in one place!


Source link

Share.

About Author

Leave A Reply