@HostBinding and @HostListener: what do they do and what are they for?

前端 未结 7 945
[愿得一人]
[愿得一人] 2020-11-30 16:57

In my meanderings around the world wide interweb, and now especially the angular.io style docs, I find many references to @HostBinding and @HostListener

7条回答
  •  长情又很酷
    2020-11-30 17:49

    Summary:

    • @HostBinding: This decorator binds a class property to a property of the host element.
    • @HostListener: This decorator binds a class method to an event of the host element.

    Example:

    import { Component, HostListener, HostBinding } from '@angular/core';
    
    @Component({
      selector: 'app-root',
      template: `

    This is nice text

    `, }) export class AppComponent { @HostBinding('style.color') color; @HostListener('click') onclick() { this.color = 'blue'; } }

    In the above example the following occurs:

    • An event listener is added to the click event which will be fired when a click event occurs anywhere within the component
    • The color property in our AppComponent class is bound to the style.color property on the component. So whenever the color property is updated so will the style.color property of our component
    • The result will be that whenever someone clicks on the component the color will be updated.

    Usage in @Directive:

    Although it can be used on component these decorators are often used in a attribute directives. When used in an @Directive the host changes the element on which the directive is placed. For example take a look at this component template:

    some paragraph

    Here p_Dir is a directive on the

    element. When @HostBinding or @HostListener is used within the directive class the host will now refer to the

    .

提交回复
热议问题