Angular @ HostBinding () and @ HostListener () usage,

Source: Internet
Author: User

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.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.