Component Communication In Angular
In this article, we will learn a few methods by that Angular Components can communicate and interact with one another. An Angular App's basic building block is the Component. There are a lot of components in a typical Angular application. Each component is responsible for a certain aspect of the user interface. To create the application's overall user interface, these components must interact or communicate with one another.
Communication between components
Components can communicate and share data in a limited number of ways. And techniques are dependent on whether or not the components have a parent-child relationship.
The three scenarios are as follows:
- Parent to Child Communication
- Child to Parent Communication
- When there isn't a parent-child relationship, interaction
Parent to Child Communication
If the Components have a parent-child relationship, the parent component can use the @input Property to transmit data to the child.
Passing Data with the @Input Decorator
In the Child Component, create a property (someProperty) and decorate it with @Input(). The property will now be marked as an input property.
export class ChildComponent { @Input() someProperty: number; }
Instantiate the Child Component in the Parent Component. Using the Property Bind Syntax, pass the value to someProperty.
<child-component [someProperty]=value></child-component>`
Listen for Input Changes
- Using the life cycle hook OnChanges or
- Using a Property Setter to Change the Value of an Input Property
Child to Parent Communication
- Listens to Events from the Perspective of a Child
- Accesses the child in the Template using a Local Variable.
- To gain a reference to the child component, using a @ViewChild.
Listens to Child Event
Uses Local Variable to access the child
<child-component #child></child-component>
To access a property of the Child Component, use the child (notice without the #). The code below shows the count of the Child Component on the screen.
<p> current count is {{child.count}} </p>
Uses a @ViewChild to get the reference to the child component
<child-component></child-component>
The ViewChild query in the component class is another approach to acquire the child component's reference.
@ViewChild(ChildComponent) child: ChildComponent;
Any method in the Child component can be called.
increment() { this.child.increment(); }
Communication when there is no relation
- Data can be shared among different components.
- When the data changes, you can use observable to alert each component.
export class TodoService { private _todo = new BehaviorSubject<Todo[]>([]); readonly todos$ = this._todo.asObservable(); ... }
this._todo.next(Object.assign([], this.todos));
this.todoService.todos$.subscribe(val=> { this.data=val; //do whatever you want to with it. })