Angular @Output() Decorator is used to data transfer from child component to the parent component.
Suppose, there are two components App component is a parent component, and the Skill Component is a child component.
App Component:- The app component has a skills array variable which has 4 skills and the Child Component (Skill Component) has the functionality to add the skill in the parent component (App Component).
Step1:- app.component.ts file
import { Component } from '@angular/core';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.scss']
})
export class AppComponent {
skills:Array<any>=['Angular','Nodejs','MongoDB','MySql'];
addSkillItem(newSkill: string) {
this.skills.push(newSkill);
}
}
Now add the child component selector app-skill into the parent component html file (app.component.html).
<h1>Employees IT Skills</h1>
<div *ngFor="let skill of skills">{{skill}}</div>
<app-skill (newSkillEvent)="addSkillItem($event)"></app-skill>
Explanation:- 1) Firstly, you have to show skills array value through *ngFor loop.
2) After that, include the Skill Component through the app-skill selector.
3) Now, add the event emitter newSkillEvent which is created in the child component.
4) Now, add the function addSkillItem which is used to add skill in the skills array.
Step2:- Now, You will create a functionality to add the @Output() Decorator in the child component Skill Component
import { Component, OnInit,Output,EventEmitter } from '@angular/core';
@Component({
selector: 'app-skill',
templateUrl: './skill.component.html',
styleUrls: ['./skill.component.scss']
})
export class SkillComponent implements OnInit {
@Output() newSkillEvent = new EventEmitter();
constructor() { }
ngOnInit(): void {
}
addNewSkill(skill){
this.newSkillEvent.emit(skill);
}
}
Explanation:- 1) First import Output and EventEmitter.
2) Now create the newSkillEvent Object through EventEmitter and use @Output decorator.
3) Now, create the function addNewSkill() which is used to emit new skills into the newSkillEvent Object.
Now, open the skill.component.html file and put the below code.
<p><strong>Add skill</strong></p>
<label>Add new skill: <input #newSkill></label>
<button (click)="addNewSkill(newSkill.value)">Add to parent's skills list</button>
Explanation:- 1) create the input box and use the #newSkill name.
2) create a button that has a click event and use the function addNewSkill().
Now, if you add a skill in the textbox and click the button then the skill will be saved into the parents’ skills array.