Home > Article > Web Front-end > Usage of @HostBinding() and @HostListener() in Angular (detailed tutorial)
This article mainly introduces the usage of Angular @HostBinding() and @HostListener(). Now I share it with you and give it as a reference.
@HostBinding() and @HostListener() are very useful when customizing instructions. @HostBinding() can add classes, styles, attributes, etc. to the host element of the instruction, and @HostListener() can listen to events on the host element.
@HostBinding() and @HostListener() are not only used in custom instructions, but are often used in custom instructions
This article is based on Angular2
Let's 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 command appRainbow
②: Define all possible colors we need to display
③: Define and use @HostBinding() to decorate color and borderColor for setting styles
④: Use @HostListener() to listen to the keydown event of the host element, Randomly assign colors to color and borderColor
OK, now use our command:
fe61655dd2b35eca51f3f5f49f70adc6
The effect will be like this:
NOTE: Don’t forget to introduce the instructions into your module
The above is what I compiled for everyone. I hope it will be helpful to everyone in the future.
Related articles:
Angular4 integrated ng2-file-upload upload component
iview table height dynamic setting method
How to install style/css loader in vue2.0
The above is the detailed content of Usage of @HostBinding() and @HostListener() in Angular (detailed tutorial). For more information, please follow other related articles on the PHP Chinese website!