Angular component interaction — Ng Data Exchange
Make every interaction count, even the small ones, they are all relevant — Shep Hyken
{ Discussion below }
1. Uni-directional data flow to child components
- Useful modules: Input from @angular/core
- In the example below, the value of salary is passed to the child component though a component directive data.
import { Component } from '@angular/core'@Component({
selector: 'app-parent',
template: `<app-child [data]="salary"></app-child>`
});export class Parent{
salary = "$ 12,000" constructor(){}
}import { Component, Input } from '@angular/core'@Component({
selector: 'app-child',
template: `<h1>My salary is {{ salary }}</h1>`
});export class Parent{
@Input() salary;constructor(){}
}
2. Child to parent interaction 1 — Using Output decorator and EventEmitter
- Here we listen for changes on a certain value in the child component and emit a value to the parent when an event occurs.
import { Component } from '@angular/core'@Component({
selector: 'app-child',
template: `<app-child (childValue)="receiveValue($event)"></app-child>`
});export class Parent{constructor(){}receiveValue(value:any){ console.log(`Received value is ${value}`);
}}import { Component, Output, EventEmitter } from '@angular/core'@Component({
selector: 'app-child',
template: `<h1 (blur)="sendProgress()">My salary is {{ salary }}</h1>`
});export class Parent{
curentProgress = 80; @Output() childValue = new EventEmitter();constructor(){}sendProgress(){
this.childValue.emit(this.currentProgress); }
}
3. Interaction with template variables
- In this example, we call the play method defined in the child component from the parent using a template variable.
import { Component } from '@angular/core'@Component({
selector: 'app-parent',
template: `
<app-child #song></app-child> <button (click)="song.play()"></button>
`
});export class Parent{
title= "Modern Streamer"constructor(){}
}import { Component } from '@angular/core'@Component({
selector: 'app-child',
template: `<h1>My playlist</h1>`
});export class Parent{
audio = new Audio(); constructor(){} play(){
this.audio.start();
}}
- In principle, angular is supposed to support uni-directional data flow
- That is data can only be passed from or changed by the parent
- Although i this case we do pass data from the child to the parent, it is generally not a recommended practice in the paradigm of state management.