EventEmitter in Angular

Component events with EventEmitter in Angular.

·

3 min read

EventEmitter in Angular

As we know Angular is based on one way/directional data flow and does not have two way data binding. so you might think how do you get a component to emit an event to another component.

EventEmitter is an Angular abstraction, and is used often, only for emitting custom Events in components.

How do we emit event in Angular?

In Angular, To emit an event from a component we use @Output and EventEmitter, And both falls under @angular/core.

EventEmitter.png View output here Output

Let's start with a basic login page with EventEmitter.

Create an Angular project with ng new .

Import ng add @angular/material (Angular Material library).

Create login-form.component.ts file

Lets make a simple form in component Template consisting Username field , password field and a login Button.

template: `
    <mat-card>
      <mat-card-title>
        <h1>Login Page</h1>
      </mat-card-title>
      <mat-card-content>
        <form [formGroup]="form" (ngSubmit)="submit()">
          <mat-form-field>
            <mat-label>Username</mat-label>
            <input type="text" matInput placeholder="Enter Username" formControlName="username"/>
          </mat-form-field>

          <mat-form-field>
            <mat-label>Password</mat-label>
            <input type="password" matInput placeholder="Enter Password" formControlName="password" />
          </mat-form-field>

          <div class="button">
            <button mat-stroked-button type="submit" color="primary">
              Login
            </button>
          </div>
        </form>
      </mat-card-content>
    </mat-card>
  `

Now lets update app.module.ts with required dependencies and import them in @ngModule

import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { FormsModule, ReactiveFormsModule } from '@angular/forms';
import { BrowserAnimationsModule } from '@angular/platform-browser/animations';
import { AppComponent } from './app.component';
import { MaterialModule } from './material.module';
import { LoginComponent } from './login-form.component';

@NgModule({
  imports: [ 
    BrowserAnimationsModule, 
    ReactiveFormsModule, 
    BrowserModule, 
    FormsModule, 
    MaterialModule ],
  declarations: [ AppComponent, LoginComponent ],
  bootstrap:    [ AppComponent ]
})
export class AppModule {}

Also import some dependencies in login-form.component.ts file Use in components with the @Output directive to emit custom events let's try this.

import { Component, OnInit, Input, Output, EventEmitter } from '@angular/core';
import { FormGroup, FormControl } from '@angular/forms';

export type Credentials = { password: string; username: string };

export class LoginComponent implements OnInit {
  @Output() credentials = new EventEmitter<Credentials>();
  form: FormGroup = new FormGroup({
    username: new FormControl(''),
    password: new FormControl('')
  });

  constructor() {}
  ngOnInit() {}
  submit() {
    this.credentials.emit(this.form.value);
  }
}

Remember do not subscribe or call any method to EventEmitter because it is only for event binding between a child and parent component, instead always call .emit() for example as we have used in above code as,

this.credentials.emit(this.form.value);

Now the parents can listen to an event in template of @component app.component.ts,

<login-form (credentials)="logCredentials($event)"></login-form>

Angular will subscribe to the credentials event and call the logCredentials() method with the data when the component triggers the next() method.

Also export the method which has input data passed through event in app.component.ts,

export class AppComponent {
  logCredentials(credentials: Credentials) {
    console.log(credentials);
  }
}

This is how your webpage/login form will look. image.png

Now enter The data and press Login button. image.png

Once Login button is clicked logCredentials($event) will be triggered, This was possible because of Angular @Output and EventEmitter image.png

View whole output here Output

For the full version of the code click on Github link .

Hope you like the tutorial stay tuned for more depth on other features too. Whysorush