Angular @Output Decorator

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 Skill Component is a child component.

App Component:- App component has a skills array variable which has 4 skills and Child Component (Skill Component) has a 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 Skill Component through 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) Firstly 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 skill into 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 #newSkill name.
2) create a button which has click event and use function addNewSkill().

Now, if you add skill in the textbox and click the button then skill will save into parents skills array.