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
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

Written by

Former Glorified Electrician(aka Electrical Engineer). Now a Software Developer working on complex Enterprise Software. Lets connect on twitter @NdamuleloNemakh

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store