Angular Component Interactions: Passing Data and Communication Methods
Angular - Component Interactions
In this tutorial, we will explore various ways and scenarios in which components interact with one another, passing data as they interact. We will also delve into different methods of data transmission between components.
Passing Data from Parent to Child with Input Binding
Components can pass data to their child components using input bindings. The child component defines input properties decorated with @Input decorator.
Example
HeroChildComponent with two input properties:
TypeScript Code:
In the example above, the second @Input aliases another child component property by naming masterName as master.
HeroParentComponent nests the child HeroChildComponent inside an *ngFor repeater:
TypeScript Code:
Intercept Input Property Changes with a Setter
An input property setter can be used to intercept and act upon a value from the parent.
Example
NameChildComponent trims the whitespace from a name and replaces an empty value with default text:
TypeScript Code:
NameParentComponent demonstrating name variations:
TypeScript Code:
Intercept Input Property Changes with ngOnChanges()
The ngOnChanges() method of the OnChanges lifecycle hook interface can monitor, detect, and act upon changes to the value of an input property.
Example
VersionChildComponent detects changes to the major and minor input properties:
TypeScript Code:
VersionParentComponent supplies the minor and major values:
TypeScript Code:
Parent Listens for Child Event
The child component exposes an EventEmitter property to emit events when something happens, which the parent binds to and reacts to those events.
Example
VoterComponent emits an event when a button is clicked:
TypeScript Code:
VoteTakerComponent binds an event handler to the child event:
TypeScript Code:
Parent Interacts with a Child via Local Variable
A parent component can read child properties or invoke child methods using a template reference variable.
Example
CountdownTimerComponent with start and stop methods:
TypeScript Code:
CountdownLocalVarParentComponent hosts the timer component:
TypeScript Code:
Parent Calls an @ViewChild()
When the parent component class requires access to child component values or methods, use the ViewChild decorator.
Example
CountdownViewChildParentComponent:
TypeScript Code:
Bidirectional Service Communication
For bidirectional communication, create a service to store and manage shared data between components.
Example
MissionService to communicate between components:
TypeScript Code:
MissionControlComponent announces missions:
TypeScript Code:
AstronautComponent listens to the mission announcement and confirms:
TypeScript Code:
Previous: Template Syntax
Next:
Component lifecycle hooks overview
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics