Edupala

Comprehensive Full Stack Development Tutorial: Learn Ionic, Angular, React, React Native, and Node.js with JavaScript

Understanding Angular output decorator or Angular Eventemitter .?

Angular output decorator

We can use the Angular output decorator in combination with the EventEmitter type to create custom events. In Angular, there is a different way of sharing data between components, and the @Outpu() decorator allows the child component to send data to its parent component.

In this tutorial, we’ll learn how to use Angular output decorator with angular event emitter to create a custom event to send data from child to parent component. Let get started.

What is Angular output decorator

The Angular @Output() decorator is linked to events that can be used to listen for data changes or other events that a parent component might be interested in and can also be used to share data up the component tree from the child to the parent component.

A component can emit events, which can be tapped into by a consuming component. The Output() decorator allows us to use binding events from a child in the parent template to respond to any DOM event in the child component.

User actions such as clicking a button, moving a mouse, submitting a form, and entering characters in the input tag raise DOM events. Binding to these events provides a way to handle any event in an Angular.

The syntax for Angular eventemitter

To bind to a target DOM event, we need to surround the DOM event name in parentheses and assign a quoted template statement to it. The parentheses (event name) represent event binding. Angular has lots of predefined events like click, keyup, input, etc… We need to add the @Output() decorator and Angular eventemitter in the child component.

@Output() eventName = new EventEmitter<Type>();

In the parent component, we have to listen to child events as below.

<child-component (eventName)="someMethod($event)"></child-component>

The parentheses brackets tell Angular that this is an event binding, which is a form of one-way binding. A child component can pass data to its parent (without knowing who the parent is) by emitting events.

Note: Important point when using output decorator and Angular event emitter.

  1. In both the child and parent components, eventName is the custom event name of your choice, it should be the same name in both components.
  2. someMethod is a method invoked when the parent component receives an event from the child component.

Passing Data from child to parent Component using Angular output decorator

An Angular allows a child component to pass a custom event upward to a parent component. Parent components need to have code that responds to things happening (events) on child components. Events should flow upwards and emit from lower-level components and to higher-level components. With event emit allows also pass data from child to parent components.

Angular output decorator

Step for creating Angular custom event or Angular eventemitter example

To demonstrate our Angular eventemitter example, we have to follow the following steps. Step1: We need to create an Angular project for Angular custom events using the Output decorator.

$ng new eventEmitterApp
cd new eventEmitterApp

Step 2: Create a child component that can pass data to parents using the @Output decorator and event emitter.

ng generate component add-student

Step 3: Import FormsModule, in the app.module.ts and create a model student so that we can apply strict data type student.

....

@NgModule({
  declarations: [
    AppComponent,
    AddStudentComponent
  ],
  imports: [
    ...
    FormsModule
  ],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule { }

Create folder model, add student.model.ts file as follows.

export interface Student {
    name: string;
    age: number;
}

Child component define Angular eventEmitter to send data to parent component

We had completed the configuration of the Angular custom event project, let’s now add a form containing the student’s name and age.

Step 4: Add a form to accept student information, which we can pass to the parent component, let the edit the add-student.component.html

<h4>Child component</h4>
<form (submit)="onAddStudent(studentForm)" #studentForm="ngForm">
  <div class="form-group">
    <label>Enter name</label>
    <input class="form-control" name="name" ngModel required>
  </div>
  <div class="form-group">
    <label>Age</label>
    <input class="form-control" type="number" name="age" ngModel>
  </div>
  <button class="btn btn-success" type="submit" value="Submit">Submit</button>
</form>

Step 5: Now in the child component typescript, we need to import Output decorator and EventEmitter from ‘@angular/core’; In Angular, a component can emit an event using @Output and EventEmitter.

import { Component, EventEmitter, Output } from '@angular/core';
import { NgForm } from '@angular/forms';
import { Student } from 'src/app/model/student.model';

@Component({
  selector: 'app-add-student',
  templateUrl: './add-student.component.html',
  styleUrls: ['./add-student.component.scss']
})
export class AddStudentComponent {
  @Output() studentCreated = new EventEmitter<Student>();

  onAddStudent(form: NgForm) {
    if (form.invalid) {
      return;
    }
    const student: Student = {
      name: form.value.name,
      age: form.value.age
    };
    this.studentCreated.emit(student);
    form.reset();
  }
}

The student component sets up an instance variable for an event emitter that outputs an event with type student data. It uses an annotation @Output() to tell Angular that parent components should be able to bind to this event.

Here’s how to set up a child component to pass custom events up to parent components:

  1. Import the EventEmitter class.
  2. Specify the custom events that your child component will emit by using the events element of the @Component directive. 
  3. Create an event emitter in your child component as an instance variable.
  4. Call the event emitter method to emit when you want to emit an event

The emit() method triggers the custom event associated with the EventEmitter, providing the listeners in the parent component with the object or value received as the method argument.

Parent component to receive data from child component

In the parent component in our case app.component.ts file, we have to add a child component selector and have to add an emitter name to create a student object.

Step 6: In the app.component.html file add the following code, to listen to the child component event.

<section>
  <app-add-student (studentCreated)="onStudentAdd($event)"></app-add-student>
  <hr>
  <div>
    <h4>List of students in Parent Component</h4>
    <div *ngFor="let student of students">
      <p><b>Name: </b> {{ student.name }} <b>Age: </b> {{ student.age }}</p>
    </div>
  </div>
</section>

In the parent component, we need to add a custom event name inside the parenthesis in the template that will listen to studentCreated event as 

(studentCreated)=“onStudentAdd($event)

On the right side of the assignment operator, we bind the method that will be called whenever the child component emits a custom event studentCreated. This event may expect some data from the child component and we can access its value by using event.target.value

Step 7: In the app.component.ts file add a student object containing some data and add the following code in the app.component.ts file as

import { Component } from '@angular/core';
import { Student } from './model/student.model';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.scss']
})
export class AppComponent {
  students: Student[] = [
    { name: 'Edupala', age: 32 },
    { name: 'Arun', age: 26 }
  ];

  onStudentAdd(student: Student) {
    this.students.push(student);
  }
}

Angular eventemitter example 2

Angular output decorator

In our second example, we’ll demonstrate notify message from the child to the parent component. Let’s first generate child components in our application.

ng generate component components/child

Let edit the child component to pass notify data from the child to the parent component.

import { Component, EventEmitter, Output } from '@angular/core';

@Component({
  selector: 'app-child',
  template:`
    <h4>Child component</h4>
    <button class="btn btn-success" (click)="sendNotify()">
       Notify parent component
    </button>`,
  styleUrls: ['./child.component.scss']
})
export class ChildComponent {
  @Output() notifyParent: EventEmitter<string> = new EventEmitter();
  

  sendNotify() {
    this.notifyParent.emit('Hi from child to parent component');
  }
}

In the parent component, we can receive notification messages from the child component.

import { Component } from '@angular/core';

@Component({
  selector: 'app-root',
  template: `
  <section>
    <h4>Parent component</h4>
    <p>Message from child component: <b>{{ messageFromParent }}</b></p>
    <hr>
    <app-child (notifyParent)="getNotification($event)"></app-child>
  </section>`,
  styleUrls: ['./app.component.scss']
})
export class AppComponent {
  messageFromParent = '';

  getNotification(message: string) {
    this.messageFromParent = message;
  }
}
Check articles on the best and latest 2022, and 2021 Angular books to read for your journey from beginner to advanced level. BEST BOOK ON ANGULAR 2022 – 2021

Conclusion
We have learned how to implement an Angular output decorator and demonstrate an example, of how we can use the @Output() decorator along with angular eventemitter allows us to send data from child to parent component.

Related posts


Understanding Angular output decorator or Angular Eventemitter .?

Leave a Reply

Your email address will not be published. Required fields are marked *

Scroll to top