Table of Contents
My doubts
Official website description
Code example
这是一个彩虹输入框,每输入一次都会改变颜色
Conclusion
About instructions and components
Summary
Home Web Front-end JS Tutorial Deep dive into HostBinding and HostListener decorators in Angular

Deep dive into HostBinding and HostListener decorators in Angular

Jul 13, 2021 pm 05:02 PM
angular Decorator

This article will take you through the two decorators in Angular-HostBinding and HostListener, and introduce the usage scenarios of these two decorators.

Deep dive into HostBinding and HostListener decorators in Angular

My doubts

I don’t know if any of you have encountered these two decorators when you are learning Angular by yourself. ——HostBinding and HostListener. When I read the API description of these two decorators on the official website, I was really puzzled. I could understand every word, but I just couldn't understand them when they were connected together. Moreover, the examples given on the official website are also very confusing, making me confused about the usage scenarios of these two APIs. [Recommended related tutorials: "angular tutorial"]

Official website description

Let's first take a look at the description of these two APIs on the official website:

HostBinding(Official website link):

is used to mark a DOM attribute as a property bound to the host and provide Configuration metadata. Angular automatically checks the host property binding during change detection, and if the binding changes, it updates the host element where the directive is located.

HostListener(Official website link):

is used to declare the DOM event to be listened to and provide the information in the event The handler method to run when this occurs.

After reading this, don’t you know what the usage scenarios of these two brothers are? In my opinion, the function of these two decorators is to facilitate us to extract complex DOM operations into one instruction to streamline the code. Not much nonsense, just read the code and you will understand it at a glance.

Code example

Suppose there is a business scenario at this time, there is an input boxinput, every time we input, the color of the words and the color of the border will change, we named it "Rainbow Input Box".

If we do not use component encapsulation, write the relevant DOM operations directly in the component. The code is as follows:

@Component({
  selector: 'app-rainbow-input-demo',
  template: `
    <h3 id="这是一个彩虹输入框-每输入一次都会改变颜色">这是一个彩虹输入框,每输入一次都会改变颜色</h3>
    <input [class]="&#39;my-input&#39;"
           type="text"
           [style]="inputStyleObj"
           (keydown)="onKeyDown()"
    />
  `,
  styles:[
    `.my-input {
        border:none;
        outline: none;
        border: 2px solid #333333;
        border-radius: 5px;
      }`
  ]
})
export class RainbowInputDemoComponent {
  //默认的颜色样式
  public inputStyleObj = {
    color:null,
    borderColor:null,
  };
  //颜色库
  public possibleColors = [
    &#39;darksalmon&#39;, &#39;hotpink&#39;, &#39;lightskyblue&#39;,
    &#39;goldenrod&#39;, &#39;peachpuff&#39;, &#39;mediumspringgreen&#39;,
    &#39;cornflowerblue&#39;, &#39;blanchedalmond&#39;, &#39;lightslategrey&#39;
  ];
  //键盘落下事件
  onKeyDown(){
    const index = Math.floor(Math.random() * this.possibleColors.length);
    //如果我们直接使用this.inputStyleObj.color = this.possibleColors[index]的话,
    //this.inputStyleObj虽然内容变了,由于它是引用类型,其地址值没有变。所以不会触发视图的重新渲染
    //在angular中,和react似的,我们直接修改引用类型不会触发重新渲染,只能覆盖它或者合并它,使其地址值发生改变,才会触发重新渲染
    //如果觉得麻烦的话,完全可以在模板中使用[style.color]和[style.borderColor]
    this.inputStyleObj = {
      color:this.possibleColors[index],
      borderColor:this.possibleColors[index],
    }
  }
}
Copy after login

The effect is as shown:

Deep dive into HostBinding and HostListener decorators in Angular

That’s it, we have implemented this function, but now there is a problem. What if we need to use this rainbowInput in other components? Do we have to copy and paste these codes every time we use it? Obviously this does not comply with the principle of component encapsulation. If you really do this, the technical manager or project manager will also blow your mind.

Then we need to encapsulate it into a component or an instruction. In this article, we first encapsulate it into a command, and we will talk about the reason later. The code is as follows:

@Directive({
  selector: &#39;[appRainbow]&#39;
})
export class RainbowInputDirective {
  public possibleColors = [
    &#39;darksalmon&#39;, &#39;hotpink&#39;, &#39;lightskyblue&#39;,
    &#39;goldenrod&#39;, &#39;peachpuff&#39;, &#39;mediumspringgreen&#39;,
    &#39;cornflowerblue&#39;, &#39;blanchedalmond&#39;, &#39;lightslategrey&#39;
  ];
  //字体颜色
  @HostBinding(&#39;style.color&#39;) color: string;
  //边框颜色
  @HostBinding(&#39;style.borderColor&#39;) borderColor: string;
  //监听键盘落下的事件
  @HostListener(&#39;keydown&#39;) onKeyDown() {
    //获取一个随机的颜色
    const index = Math.floor(Math.random() * this.possibleColors.length);
    this.color = this.borderColor = this.possibleColors[index];
  }
}

@Component({
  selector: &#39;app-rainbow-input-demo&#39;,
  template: `
    <h3 id="这是一个彩虹输入框-每输入一次都会改变颜色">这是一个彩虹输入框,每输入一次都会改变颜色</h3>
    <input [class]="&#39;my-input&#39;" type="text" appRainbow />
  `,
  styles:[
   	//省略,和上面相同
  ]
})
export class RainbowInputDemoComponent {}
Copy after login

Just like the above code, we extracted the repeated logic, which greatly improved the maintainability and beauty of the code.

Conclusion

In the code we can see that the function of @HostBinding is actually to bind a certain attribute to the host element, but this attributeNot just any attribute. This attribute refers to the attributes supported in angular templates. In fact, @HostBinding is equivalent to [] or bind- in the template. In the same way, @HostListener is equivalent to () or on- in the template. This allows us to bind attributes and methods to the host element in the instruction. The effect achieved is the same as our first direct writing of (keydow) and [style] It's the same on the template. Therefore, the strings in these two decorators cannot be written casually.

About instructions and components

However, in fact, in angular, the difference between components and instructions is not particularly big, because the component decorator @Component in angular is inherited from @Directive.

In fact, it is not impossible for us to encapsulate this DOM operation into a component. The code is as follows

@Component({
  selector:&#39;input[appRainbow]&#39;
})
Copy after login

, but it is really not much different from the instruction writing method:

@Directive({
  selector: &#39;[appRainbow]&#39;
})
Copy after login

.

Summary

@HostBinding is equivalent to [] or bind-;

on the template @HostListener is equivalent to () or on- on the template;

is the data and method binding in the instructions provided by Angular in order not to let us directly operate the DOM. Certainly.

For more programming-related knowledge, please visit: Programming Teaching! !

The above is the detailed content of Deep dive into HostBinding and HostListener decorators in Angular. For more information, please follow other related articles on the PHP Chinese website!

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

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Detailed explanation of angular learning state manager NgRx Detailed explanation of angular learning state manager NgRx May 25, 2022 am 11:01 AM

This article will give you an in-depth understanding of Angular's state manager NgRx and introduce how to use NgRx. I hope it will be helpful to you!

How to install Angular on Ubuntu 24.04 How to install Angular on Ubuntu 24.04 Mar 23, 2024 pm 12:20 PM

Angular.js is a freely accessible JavaScript platform for creating dynamic applications. It allows you to express various aspects of your application quickly and clearly by extending the syntax of HTML as a template language. Angular.js provides a range of tools to help you write, update and test your code. Additionally, it provides many features such as routing and form management. This guide will discuss how to install Angular on Ubuntu24. First, you need to install Node.js. Node.js is a JavaScript running environment based on the ChromeV8 engine that allows you to run JavaScript code on the server side. To be in Ub

An article exploring server-side rendering (SSR) in Angular An article exploring server-side rendering (SSR) in Angular Dec 27, 2022 pm 07:24 PM

Do you know Angular Universal? It can help the website provide better SEO support!

How to use PHP and Angular for front-end development How to use PHP and Angular for front-end development May 11, 2023 pm 04:04 PM

With the rapid development of the Internet, front-end development technology is also constantly improving and iterating. PHP and Angular are two technologies widely used in front-end development. PHP is a server-side scripting language that can handle tasks such as processing forms, generating dynamic pages, and managing access permissions. Angular is a JavaScript framework that can be used to develop single-page applications and build componentized web applications. This article will introduce how to use PHP and Angular for front-end development, and how to combine them

A brief analysis of how to use monaco-editor in angular A brief analysis of how to use monaco-editor in angular Oct 17, 2022 pm 08:04 PM

How to use monaco-editor in angular? The following article records the use of monaco-editor in angular that was used in a recent business. I hope it will be helpful to everyone!

A brief analysis of independent components in Angular and see how to use them A brief analysis of independent components in Angular and see how to use them Jun 23, 2022 pm 03:49 PM

This article will take you through the independent components in Angular, how to create an independent component in Angular, and how to import existing modules into the independent component. I hope it will be helpful to you!

Angular components and their display properties: understanding non-block default values Angular components and their display properties: understanding non-block default values Mar 15, 2024 pm 04:51 PM

The default display behavior for components in the Angular framework is not for block-level elements. This design choice promotes encapsulation of component styles and encourages developers to consciously define how each component is displayed. By explicitly setting the CSS property display, the display of Angular components can be fully controlled to achieve the desired layout and responsiveness.

What should I do if the project is too big? How to split Angular projects reasonably? What should I do if the project is too big? How to split Angular projects reasonably? Jul 26, 2022 pm 07:18 PM

The Angular project is too large, how to split it reasonably? The following article will introduce to you how to reasonably split Angular projects. I hope it will be helpful to you!

See all articles