Home > Article > Web Front-end > The difference between using @HostBinding() and @HostListener() in AngularJS
This time I will bring you the difference in using @HostBinding() and @HostListener() in AngularJS, and notes when using @HostBinding() and @HostListener() in AngularJS What are the matters ? Below are actual cases, let’s take a look at them.
@HostBinding() and @HostListener() are very useful when customizing instructions. @HostBinding() can add classes, styles, attributes, etc. to the host element of the directive, and @HostListener() can listen to events on the host element.
@HostBinding() and @HostListener() are not only used in custom instructions, but are used more in custom instructions
This article is based on Angular2
Next, we learn the usage of @HostBinding() and @HostListener() by implementing a command that changes the font and border color in real time during input.
import { Directive, HostBinding, HostListener } from '@angular/core'; @Directive({ selector: '[appRainbow]'① }) export class RainbowDirective{ possibleColors = [ 'darksalmon', 'hotpink', 'lightskyblue', 'goldenrod', 'peachpuff', 'mediumspringgreen', 'cornflowerblue', 'blanchedalmond', 'lightslategrey' ];② @HostBinding('style.color') color: string; @HostBinding('style.borderColor') borderColor: string;③ @HostListener('keydown') onKeydown(){④ const colorPick = Math.floor(Math.random() * this.possibleColors.length); this.color = this.borderColor = this.possibleColors[colorPick]; } }
Let’s talk about the main parts of the above code:
①: Name our directive appRainbow
②: Define all possible colors we need to display
③: Define and use @HostBinding() to decorate color and borderColor for setting styles
④: Use @HostListener() listens to the keydown event of the host element and randomly assigns colors to color and borderColor
I believe you have mastered the method after reading the case in this article. For more exciting information, please pay attention to other related articles on the PHP Chinese website!
Recommended reading:
springmvc cannot accept parameters when axios sends a request
How to implement the network request function through axios
The above is the detailed content of The difference between using @HostBinding() and @HostListener() in AngularJS. For more information, please follow other related articles on the PHP Chinese website!