This article is a mirror article of machine translation, please click here to jump to the original article.

View: 12212|Reply: 0

[Angular] Angular event binding/attribute bindings @HostListener, @HostBinding

[Copy link]
Posted on 6/26/2019 2:42:08 PM | | | |
Before we get into the HostListener and HostBinding property decorators, let's take a look at the host element.

The concept of a host element applies to both instructions and components. For instructions, the concept is fairly simple. The element that applies the instruction is the host element. Let's say we've declared a HighlightDirective directive (selector: '[exeHighlight]'):

In the above HTML code, the p element is the host element. If the directive is applied to a custom component, such as:

In this case, the exe-counter custom element is the host element.

HostListener is a property decorator that adds event listening to host elements.

In Angular, we can use the HostBinding decorator to implement property binding of elements.

This directive demonstrates how to use the HostListener decorator to listen for user click events

In addition, we can also listen for events generated by objects other than the host element, such as window or document or body
The target can be window, document or body




@HostBinding() and @HostListener() are useful when customizing instructions. @HostBinding() can add classes, styles, attributes, etc. to the host element of the command, while @HostListener() can listen to events on the host element.

Example: Implement a font and border color that changes the font and border color in real time as you type

Let's talk about the main part of the code above:
(1): Name our command appRainbow
(2): Define all the possible colors we need to show
(3): Define and decorate color and borderColor with @HostBinding() for styling
(4): Use @HostListener() to listen to the keydown event of the host element and randomly assign colors to color and borderColor

Use this command on the page:

The effect is as follows:







Previous:The principle of SM2 digital signature verification
Next:js determines whether js functions and variables exist
Disclaimer:
All software, programming materials or articles published by Code Farmer Network are only for learning and research purposes; The above content shall not be used for commercial or illegal purposes, otherwise, users shall bear all consequences. The information on this site comes from the Internet, and copyright disputes have nothing to do with this site. You must completely delete the above content from your computer within 24 hours of downloading. If you like the program, please support genuine software, purchase registration, and get better genuine services. If there is any infringement, please contact us by email.

Mail To:help@itsvse.com