Method Decorator in Angular 8 | What is HostListener

What is Decorators



Decorators are a design that is used to separate modification or decoration of a class without modifying the original source code.

Decorators are of 4 types.


In this article we will discuss about Method decorator.


What is method decorator

Method decorator is declared just before method declaration.This can be used to observe,modify a method definition.

@HostListener is a good example of method decorator .
When any event happen in our host then we want decorated method to be called.


Method Decorator
Method Decorator


To implement @HostListener decorator we need to import HostListener Interface.


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

Lets implement method decorator with an example.

Implementation

1.Create a folder called Test under App folder and add 2 files called Test.component.html and Test.component.ts.

2.Under Test.component.html  we need to add the below code.

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8" />
    <title></title>
</head>
<body>
    <b>
        My Text
        <br />
        <br />
        Your Text
    </b>
</body>
</html>


3.Under Test.component.ts  we need to add the below code.

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

@Component({
    selector: 'example-component',
    templateUrl: 'app/Test/Test.component.html',
})
export class ExampleComponent {
    @HostListener('click', ['$event'])
    OnHostClicked() {
        alert('You clicked the host');
    }
    @HostListener('mouseover', ['$event'])
    OnMouseOver() {
        alert('Mouse Over');
    }
}


In the above code we import HostListener interface.
Then added @HostListener('click', ['$event']) which allow the method to fire when click event occurs.

4. Write the below code under the App.component.ts .


<example-component></example-component>

5.Register the component class in app.module.ts.

We are done !!!!!!!!!
Run the application and you can see a alert once you mouse over the text.

Thanks............


Share:

No comments:

Post a Comment

Contact for Azure Training

Name

Email *

Message *

Subscribe YouTube

Total Pageviews

Popular Posts

Labels

Recent Posts