This time I will bring you AngularJSWhat is the difference between @HostBinding() and @HostListener(), and Notes on using @HostBinding() and @HostListener() in AngularJSWhat are they? Here are actual cases. Let’s take a look.
@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 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 instruction appRainbow
②: Define all possible colors we need to display
③: Define and decorate color and borderColor with @HostBinding() for setting styles
④: Use @HostListener() to listen to the keydown event of the host element and randomly assign colors to color and borderColor
OK, let’s do it now Use our command:
The effect will be like this:
Why axios http request cannot be used in vue2
Why springMVC cannot receive parameters when sending post request
The above is the detailed content of What is the difference between @HostBinding() and @HostListener() in AngularJS. For more information, please follow other related articles on the PHP Chinese website!