Home > Web Front-end > JS Tutorial > Usage of @HostBinding() and @HostListener() in Angular (detailed tutorial)

Usage of @HostBinding() and @HostListener() in Angular (detailed tutorial)

亚连
Release: 2018-06-01 11:47:19
Original
3259 people have browsed it

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];
 }
}
Copy after login

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:

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!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template