How to implement Angular output decorator .?

In Angular, there are different ways of sharing data and communicating between components. Both @Input() property binding and Angular output decorator or (angular event binding) via component are also the technique of communicating between child/parent related components.

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 output decorator.

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, and input, etc…

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

The parentheses brackets tell Angular that this is an event binding, which is a form of one-way binding where data flows from the element to the rest of the application. In articles, we will explore event binding in two cases.

Angular event binding example on input event binding:

Here we will bind input event binding on input tag, this allows us to capture the value of character type in the input tag.

In view add input tag with input event.
  <input [value]="name" (input)="typeCharacter($event)" />
  
In component add code to capture input event and display the value as 
  typeCharacter(event) {
    console.log(event.target.value);
  }

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.

We will learn custom event binding with an example.
1. Create a new project
$ng new myApps

2. Create a component called add-student
$ng generate component add-student

3. Create a Student model
In the app folder, create a file called student.ts add the following code to create a student model.

Angular output decorator example

Screenshot of custom event binding

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

Step 4: In a child, component add-student.component.html add following code

<form (submit)="onAddStudent(studentForm)" #studentForm="ngForm">
    Enter name:<br>
    <input type="text" name="name" ngModel required>
    <br>
    Age :<br>
    <input type="number" name="age" ngModel required>
    <br><br>
    <input type="submit" value="Submit">
</form>

Step 5: Add the following code in the child component (add-student.component.ts) file. 

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

@Component({
  selector: 'app-add-student',
  templateUrl: './add-student.component.html',
  styleUrls: ['./add-student.component.sass']
})
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.

In the child component, we are using ngForm from @angular/forms, we have to import the form module in our app.module.ts file as 

import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { FormsModule } from "@angular/forms";
.....
import { AddStudentComponent } from './add-student/add-student.component';

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

Step 6:  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. In the home.component.html file add the following code

<app-add-student (studentCreated)="onStudentAdd($event)"></app-add-student>

<div *ngFor="let student of students">
    <p><b>Name: </b> {{ student.name }}    <b>Age: </b> {{ student.age }}</p>
</div>
<router-outlet></router-outlet>

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, Input } from '@angular/core';
import { Student } from './student';
@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.sass']
})
export class AppComponent {
  students: Student[] = [
    { name: 'Edupala', age: 32 },
    { name: 'Arun', age:26 }
  ];

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

Check more information on angular event binding on official angular documentation.

Conclusion
We have learned how to implement an Angular output decorator and demonstrate an example, how we can use @Output(), decorator, to emit events for passing data from child to parent component.

Related posts


Leave a Comment

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

Scroll to Top