在我漫游的世界各地互联网,现在尤其是角。我发现很多@HostBinding和@HostListener的引用。它们似乎是相当基本的,但不幸的是,目前它们的文档有点粗略。

谁能解释一下它们是什么,它们是如何工作的,并举例说明它们的用法吗?


当前回答

有一件事使这个主题更加混乱,那就是装饰者的概念不是很清楚,当我们考虑像……

@HostBinding('attr.something') 
get something() { 
    return this.somethingElse; 
 }

它可以工作,因为它是一个get访问器。你不能使用等价的函数:

@HostBinding('attr.something') 
something() { 
    return this.somethingElse; 
 }

否则,使用@HostBinding的好处是它确保在绑定值发生变化时运行更改检测。

其他回答

方法修饰符:

@HostBinding:动态绑定自定义逻辑到Host元素

 @HostBinding('class.active')
 activeClass = false;

@HostListen:监听Host元素上的事件

@HostListener('click')
 activeFunction(){
    this.activeClass = !this.activeClass;
 }

主机元素:

  <button type='button' class="btn btn-primary btn-sm" appHost>Host</button>

你检查过这些正式的文件了吗?

HostListener -声明一个主机监听器。当宿主元素触发指定的事件时,Angular将调用修饰过的方法。

@HostListener——将监听由@HostListener声明的主机元素发出的事件。

HostBinding -声明一个主机属性绑定。Angular会在变更检测时自动检查主机属性绑定。如果绑定发生变化,它将更新指令的host元素。

@HostBinding -将属性绑定到主机元素,如果绑定改变,HostBinding将更新主机元素。


注意:这两个链接最近已被删除。样式指南中的“HostBinding-HostListening”部分可能是一个有用的选择,直到链接返回。


下面是一个简单的代码示例,可以帮助您理解这是什么意思:

演示:下面是plunker中的现场演示-“关于@HostListener和@HostBinding的一个简单示例”

This example binds a role property -- declared with @HostBinding -- to the host's element Recall that role is an attribute, since we're using attr.role. <p myDir> becomes <p mydir="" role="admin"> when you view it in developer tools. It then listens to the onClick event declared with @HostListener, attached to the component's host element, changing role with each click. The change when the <p myDir> is clicked is that its opening tag changes from <p mydir="" role="admin"> to <p mydir="" role="guest"> and back.

directives.ts

import {Component,HostListener,Directive,HostBinding,Input} from '@angular/core';

@Directive({selector: '[myDir]'})
export class HostDirective {
    @HostBinding('attr.role') role = 'admin';
    @HostListener('click') onClick() {
        this.role= this.role === 'admin' ? 'guest' : 'admin';
    }
}

AppComponent.ts

import { Component,ElementRef,ViewChild } from '@angular/core';
import {HostDirective} from './directives';

@Component({
    selector: 'my-app',
    template:
        `
        <p myDir>
            Host Element 
            <br><br>
        
            We have a (HostListener) listening to this host's 
            <b>click event</b> declared with @HostListener
        
            <br><br>
        
            And we have a (HostBinding) binding <b>the role property</b>
            to host element declared with @HostBinding 
            and checking host's property binding updates.
            
            If any property change is found I will update it.
        </p>
        
        <div>
            View this change in the DOM of the host element 
            by opening developer tools, clicking the host element in the UI. 
        
            The role attribute's changes will be visible in the DOM.
        </div> 
        `,
    directives: [HostDirective]
})
export class AppComponent {}

下面是一个基本的悬停例子。

组件的模板属性:

模板

<!-- attention, we have the c_highlight class -->
<!-- c_highlight is the selector property value of the directive -->

<p class="c_highlight">
    Some text.
</p>

我们的指令

import {Component,HostListener,Directive,HostBinding} from '@angular/core';

@Directive({
    // this directive will work only if the DOM el has the c_highlight class
    selector: '.c_highlight'
 })
export class HostDirective {

  // we could pass lots of thing to the HostBinding function. 
  // like class.valid or attr.required etc.

  @HostBinding('style.backgroundColor') c_colorrr = "red"; 

  @HostListener('mouseenter') c_onEnterrr() {
   this.c_colorrr= "blue" ;
  }

  @HostListener('mouseleave') c_onLeaveee() {
   this.c_colorrr = "yellow" ;
  } 
}
// begginers
@Component({
  selector: 'custom-comp',
  template: ` <div class="my-class" (click)="onClick()">CLICK ME</div> `,
})
export class CustomComp {
  onClick = () => console.log('click event');
}

// pros
@Component({
  selector: 'custom-comp',
  template: ` CLICK ME `,
})
export class CustomComp {
  @HostBinding('class') class = 'my-class';
  @HostListener('click') onClick = () => console.log('click event');
}

// experts
@Component({
  selector: 'custom-comp',
  template: ` CLICK ME `,
  host: {
    class: 'my-class',
    '(click)': 'onClick()',
  },
})
export class CustomComp {
  onClick = () => console.log('click event');
}

------------------------------------------------
The 1st way will result in:
<custom-comp>
   <div class="my-class" (click)="onClick()">
      CLICK ME
   <div>
</custom-comp>

The last 2 ways will result in:
<custom-comp class="my-class" (click)="onClick()">
   CLICK ME
</custom-comp>

一个帮助我记住他们做什么的小技巧——

HostBinding括号(“价值”);与[value]="myValue"完全相同

And

HostListener('click') myClick(){}与(click)="myClick()"完全相同


HostBinding和HostListener是用指令编写的 而其他的……和……]被写在(组件的)模板中。