Angular @ HostBinding () and @ HostListener () usage,
@ HostBinding () and @ HostListener () are useful in custom commands. @ HostBinding () can add classes, styles, and attributes to the host element of the command, while @ HostListener () can listen to events on the host element.
@ HostBinding () and @ HostListener () are not only used in custom commands, but are used in many custom commands.
This article is based on Angular2 +
The following describes how to use @ HostBinding () and @ HostListener () to change 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 to be displayed
③: Define and use @ HostBinding () to decorate the color and borderColor for setting the style.
④: Use @ HostListener () to listen to the keydown event of the host element, and randomly assign the color and borderColor
OK. Now let's use our command:
<Input appRainbow>
The effect is as follows:
NOTE: Don't forget to introduce commands into your module.
The above is all the content of this article. I hope it will be helpful for your learning and support for helping customers.