Component Interaction In Angular
Component interaction refers to communication between two or more components created in an Angular application.
This article is a bit long and filled with code snippets, bear with me kindly.
Lets get to it...
1. Passing Data From Parent Component to Child Component
Angular provides an input decorator which is used to pass data from a parent component to a child component.
---------------------------------------------------------------------------------------------------------------
Inputs from parents can also be aliased as seen. The aliased name can now be reused in the child component without changing the parent component.
The input can also be intercepted and altered as desired in the child component using getters and setters as seen below:
The input can also be intercepted using ngOnChanges lifecycle method. In an earlier article,
about lifecycle methods it was discussed that this lifecycle method is loaded first and it is where the input properties are defined in a component.
2. Parent Listening To events in the child component
Angular provides an output decorator and an EventEmitter property that is used to expose events happening in the child to the parent component.
领英推荐
the parent, the event is received by a special argument $event which represents the value of the event from the child component.
The $event type can be and should be defined in both parent and child components to ensure narrow typing and type guards when passing data from child to parent.
3. Parent Interacts with child using local variable
The parent component cannot read any properties or call any methods defined in the child. However, through the use of a template reference variable.
The methods and properties accessed must also be public.
4. Parent calls @ViewChild Decorator
This approach heavily borrowed from the interaction through a reference. However, this approach does not use the parent template but the parent component. It requires the ViewChild decorator and the AfterViewInIt lifecycle.
The lifecycle is added because any property that is needed from the child in the parent cannot be accessed only until the parent’s view has been initialized.
5. ?Parent and children communicate using a service
The final way that parents and children can communicate is through a shared service. This method utilizes observables. Both parent and child subscribe to an observable created in the service.
The service is then called with methods that alter these observables before passing the new values to the children using .next() for observables.
After that loooong talk that's all I got today! Thank you for your time.