Angular EventEmitter and Services
Learn how to use the Angular EventEmitter and Angular services to manage events in TypeScript.
We'll cover the following...
Angular EventEmitter
When a user clicks on the “login” button of our toolbar, we will need to show the login panel, which will allow the user to enter their username and password.
The event handler that traps the click event on the “login” button, however, is a part of the user-details component that renders the buttons onto the screen. Angular provides an EventEmitter
class,
which allows child components to send messages to their parents.
Let’s explore this mechanism by modifying our UserDetailsComponent
class as follows:
import { EventEmitter, Output } from '@angular/core';@Component({selector: 'app-user-details',templateUrl: './user-details.component.html',styleUrls: ['./user-details.component.scss'],})export class UserDetailsComponent implements OnInit {loggedInUserName: string = 'logged_in_user';constructor() {}ngOnInit(): void {}@Output() notify = new EventEmitter();onLoginClicked() {console.log(`UserDetailsComponent : onLoginClicked()`);this.notify.emit('UserDetailsComponent : emit value');}}
Here, we have added a class property named notify
on line 19 that is a new instance of the EventEmitter
class. We have also used a class property decorator named @Output()
on line 15 to mark the notify
property as an output property. We have also updated our onLoginClicked
function to call the emit
function of the notify
property. This emit
function takes a single parameter of type any
. In this case, we have supplied a single-string argument.
Now that we are emitting an event, we will need to consume this event and do
something with it. Angular provides the (notify
) HTML template event, which is available on the parent component of the component that is emitting the event.
This means that we will need to modify the header.component.html
file to register for this event and also modify the ...