Angular @Output : Binding to Custom Events
introduction:
here we are having a child component and we will be sending information from child to the parent so we are outputting information from child to the parent, or we can say we are binding our own custom events to the parent component.
child component.
ts file
- here we have two property server name and content that will be updated using ngModel and we have function that will be triggered by onclick once that is clicked we will emit the event to the parent component.
import { Component, OnInit,EventEmitter, Output } from '@angular/core';
@Component({
selector: 'app-cockpit',
templateUrl: './cockpit.component.html',
styleUrls: ['./cockpit.component.css']
})
export class CockpitComponent implements OnInit {
newServerName = '';
newServerContent = '';
@Output() serverCreated = new EventEmitter<{serverName:string,serverContent:string}>();;
@Output() blueprintCreated = new EventEmitter<{serverName:string,serverContent:string}>();
constructor() { }
ngOnInit(): void {
}
onAddServer() {
this.serverCreated.emit({
serverName:this.newServerName,
serverContent:this.newServerContent
})
}
onAddBlueprint() {
this.blueprintCreated.emit({
serverName:this.newServerName,
serverContent:this.newServerContent
})
}
}
Parent Component .
parent component HTML, here in the cockpit component, when the custom event trigger from child serverCreated we will call the method onServerAdded, with the information and then take the information and store that in the array and later we can pass that to the child component.
Parent component template [HTML]
<div class="container">
<app-cockpit (serverCreated)="onServerAdded($event)" (blueprintCreated)="onBlueprintAdded($event)"></app-cockpit>
<hr>
<div class=" row">
<div class="col-xs-12">
<app-server-element *ngFor="let serverElement of serverElements" [srvElement]="serverElement">
</app-server-element>
</div>
</div>
</div>
Parent Component [TS]
import { Component } from '@angular/core';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
serverElements = [
{
type:'server',
name:'firstserver',
content:'first server contenet'
},
];
onServerAdded(serverData:{serverName:string,serverContent:string}) {
this.serverElements.push({
type: 'server',
name: serverData.serverName,
content: serverData.serverContent
});
}
onBlueprintAdded(bluePrintData:{serverName:string,serverContent:string}) {
this.serverElements.push({
type: 'blueprint',
name: bluePrintData.serverName,
content: bluePrintData.serverContent
});
}
}