How to Share Sharing Data Between Angular Components

This article applies to every Angular version, including 9. To share component data you can use the following:

  • @Input — property binding
  • @Output and EventEmitter — event binding
  • @ViewChild andAfterViewInit

Let’s look at each of them in turn.

@Input — Property Binding

If you want to pass data from the parent component to the child component, you need to use two things: @Input and property binding.

In this example, we set in the child component a variable named childExample, which is a string. We set Angular’s@Input decorator in front of the variable.

This is image title

Code display by Carbon

This gives us the option to add an attribute to the selector (``) of the child, as highlighted in the example below:

This is image title

In the parent, we declare a variable named parentExample. We give it a value of [childExample]. The result is that the text “Hello Angular 7” is displayed in the child component.

@Output & EventEmitter — Event Binding

With @Output and EventEmitter it’s the other way around. You can pass data back from the child to the parent component. Again, we declare a variable in the child, but this time with the@Output decorator and a new EventEmitter:

This is image title

We want to emit an event to the parent component by doing the following:

This is image title

On every button click in the child component we’re passing the text “Hello Angular 7” to a parent component.

This is image title

In our parent component we can now set an event to the child selector (``). As you can see, we use the exampleOutput from the child, which has as value a method called exampleMethodParent with parameter $event.

This is image title

Now, on every button click in the child, we get a text through an event in our parent method. In this method, we give example the value of $event. Through interpolation ({{ exampleParent }}), we can now see our child’s example text.

@ViewChild & AfterViewInit

The third way to pass data is by using @ViewChild and AfterViewInit. With this final option, we can refer to a child component and access their variables inside our parent component.

This is image title

The decorator is set in the parent component. We declare the following in the class:

This is image title

We also need to implement the AfterViewInit lifecycle hook, because the child is not available until the view is initialized. In the ngAfterViewInit() method we access the exampleChild from the ChildComponent and give the value to the exampleParent variable.

This is image title

Our complete ParentComponent will look like this:

This is image title

Again, through interpolation ({{ exampleParent }}), we can now see our child’s example text.

Thank you for reading!

#angular #angular9 #javascript #programming

How to Share Sharing Data Between Angular Components
37.80 GEEK