Parent-child component interaction in Angular 11

0

For beginners, the component-based architecture of Angular takes a bit of getting used to. Unlike the object-oriented design (OOP) of programming languages ​​like Java, Angular is not able to apply encapsulation with quite the same voracity, mainly due to JavaScript’s unlimited access to the DOM. But, as they say, just because you CAN do something, that doesn’t mean you SHOULD. So rather than relying on the compiler to keep you from breaking the rules, it’s best to learn to do things the ‘Angular way’ from the start so that you code your applications to enforce encapsulation. components rather than undermining it. To that end, this tutorial will provide an overview of how to pass data between parent and child components – both from parent to child and vice versa.

Demo application

I usually post a link to the demo at the end of the article, but this time I’m presenting it upstream, so that the stage is set for the coding to come. Hope you are hungry, because this demo takes pizza orders!

Above the horizontal line we have the parent content, which includes text entry and a button to submit special requests. Below that is a list of toppings, selected from the child component below. Likewise, special requests are displayed in the child under the toppings list. (I kept it in the top 10 toppings for demo purposes)

Using this configuration, the parent must pass special requests to the child component, while the child must send the selected toppings to the parent.

You can find the demo on codesandbox.io.

Passing data from the parent component to a child

In the demo application, the child component, whose selector is “child-app“, can be seen at the bottom of the main app.component.html template file:

Welcome to Rob's Pizza Parlour!

Selected Toppings:

  1. {{topping}}
(Child Component Below)
</app-child>

There you will notice that it has two special attributes:

  1. [requests]= “requests”
  2. (selectedToppingsEmitter) = “setSelectedToppings ($ event) ”

For now, we will focus on the first (request) attribute. It’s a public variable that we pass to the app-child component:

export class AppComponent {
  public requests="";
  
  //...
}

In order to consume the value of demand, the Child component must define a @Contribution decorator as follows:

export class ChildComponent {
  @Input() requests: string = '';
  
  //...
}

While I assigned the variable the same name in parent and child for consistency, there is absolutely no requirement to do so.

We can now treat the request variable like any other. Since we don’t need to massage the data, we can reference it directly in the model using double braces {{}}:

Special requests

{{requests}}

Passing data from a child component to the parent

Just like a @Contribution decorator defines a variable that comes from the parent component, a @Production() decorator defines a variable to pass to the parent. Or rather, it defines a Event emitter It’s okay send () given to parent. the Event emitter is configured so that it knows what type of data it is going to process. In our case, this will be the selectedToppings array of strings:

export class ChildComponent {
  
  @Input() requests: string = '';
  @Output() selectedToppingsEmitter = new EventEmitter();

  private selectedToppings: string[] = [];
  //...
}

The next step is to actually issue the Selected garnishes. We will do it in the checkValue () method. It is invoked whenever a trim checkbox is checked or unchecked. First, we add or remove the element from the array. Next, we emit the entire updated array to the parent:

public checkValue(event: Event) {
  const checkbox: HTMLInputElement | null = (event.target as HTMLInputElement);
  if (checkbox) {
    if (checkbox.checked) {
      this.selectedToppings.push(checkbox.value);
    } else {
      const index = this.selectedToppings.indexOf(checkbox.value);
      this.selectedToppings.splice(index, 1);
    }
    this.selectedToppingsEmitter.emit(this.selectedToppings);
  }
}

To invoke the checkValue () method, we need to bind it to the checkbox change event like this:

Toppings List

Back in the parent model, the selectedGasketsEmitter is linked to a public component method. Note that, in this case, the Issuer’s name must exactly match that of the child. The name of the linked method may be what we like though. You can see it here in the markup for the app-child element:

</app-child>

In the setSelectedToppings () method, we will define our local garnishes variable at emission Selected garnishes. As such, it’s really nothing more than a smuggler:

export class AppComponent {
  public toppings: string[] = [];
  public requests="";

  setSelectedToppings(selectedToppings: string[]) {
    this.toppings = selectedToppings;
  }
}

Finally, a * ngFor loop is used to list all the selected toppings in an ordered list:

Selected Toppings:

  1. {{topping}}

Conclusion

In this tutorial, we learned how to pass data between parent and child components, both from parent to child and vice versa. Next time we will answer the question of how to answer @Contribution parameter updates as well as how to intercept them before outputting them to our template files.


Source link

Share.

About Author

Leave A Reply