@HostBinding和@HostListener:他们做了什么,他们有什么用?

ser*_*gpa 166 angular-services angular

在我的蜿蜒环绕世界各地的interweb,现在特别是angular.io风格的文档,我发现许多引用@HostBinding@HostListener.看起来它们非常基础,但不幸的是,目前它们的文档有点粗略.

任何人都可以解释它们是什么,它们如何工作并举例说明它们的用法?

mic*_*yks 123

你查过这些官方文档了吗?

HostListener - 声明主机侦听器.当host元素发出指定的事件时,Anngular将调用trim方法.
# HostListener -将听取主元素,@HostListener声明发出该事件.

HostBinding -Declares主机属性binding.Angular在更改检测期间自动检查主机属性绑定.如果绑定发生更改,它将更新指令的host元素.
# HostBinding -将绑定属性Host元素,如果有约束力的变化,HostBinding将更新主机元素.


注意:最近删除了这两个链接.所以,请尝试从HostBinding-HostListening了解它, 因为还没有适当的文档.


我试着做一个简单的例子,让你更好地理解,

演示:检查以下示例live in plunker - 一个关于@HostListener和@HostBinding的简单示例

这个例子绑定一个@HostListener声明了@HostListener@HostBinding和监听HostBinding与申报role@HostBinding

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';
  }
}
Run Code Online (Sandbox Code Playgroud)

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 {}
Run Code Online (Sandbox Code Playgroud)


Sha*_*.io 99

一个快速提示,帮助我记住他们做了什么 -

HostBinding('value') myValue; 与...完全相同 [value]="myValue"

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


HostBindingHostListener写入指示和其他的(...)[..]被写入内部模板(组件).

  • 啊,由于这个答案,它点击了(双关语).`@ H​​ostListener`是你在DOM上没有任何东西用于典型事件绑定的方法,例如我的情况下的键盘输入. (8认同)

ser*_*kan 46

这是一个基本的悬停示例.

组件的模板属性:

模板

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

<p class="c_highlight">
    Some text.
</p>
Run Code Online (Sandbox Code Playgroud)

而我们的指示

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" ;
  } 
}
Run Code Online (Sandbox Code Playgroud)

  • 我不认为这个被接受的答案是对所提问题的回答.你愿意提供一些解释吗?像c_colorrr,c_onEnterrr(),c_onLeaveeee在这个特定的代码片段中做什么? (27认同)

alt*_*ler 32

另一个好处@HostBinding是,@Input如果你的绑定直接依赖于输入,你可以将它组合起来,例如:

@HostBinding('class.fixed-thing')
@Input()
fixed: boolean;
Run Code Online (Sandbox Code Playgroud)

  • 我认为我缺少的是这与仅使用“@HostBinding”有何不同。什么时候需要使用`@Input`? (2认同)

Don*_*one 11

有一件事给这个问题增加了混乱,装饰者的想法不是很明确,当我们考虑像...

@HostBinding('attr.something') 
get something() { 
    return this.somethingElse; 
 }
Run Code Online (Sandbox Code Playgroud)

它有效,因为它是一个get存取器.您无法使用等效的函数:

@HostBinding('attr.something') 
something() { 
    return this.somethingElse; 
 }
Run Code Online (Sandbox Code Playgroud)

否则,使用的好处@HostBinding是确保在绑定值更改时运行更改检测.


Dav*_*pes 11

// 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.my-class') className = true;
  @HostListener('click') onClick = () => this.className = false;
}

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

第一种方式将导致:

// 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.my-class') className = true;
  @HostListener('click') onClick = () => this.className = false;
}

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

第二种和第三种方式将导致:

<custom-comp>
   <div class="my-class" (click)="onClick()">
      CLICK ME
   <div>
</custom-comp>
Run Code Online (Sandbox Code Playgroud)

注意:二号你找到复活节彩蛋了吗?

  • 感谢您贡献答案。请您编辑您的答案以包含对您的代码的解释吗?这将帮助未来的读者更好地理解正在发生的事情,特别是那些刚接触该语言并难以理解这些概念的社区成员。 (3认同)

Wil*_*een 7

摘要:

  • @HostBinding:此装饰器将类属性绑定到宿主元素的属性。
  • @HostListener:此装饰器将类方法绑定到host元素的事件。

例:

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

@Component({
  selector: 'app-root',
  template: `<p>This is nice text<p>`,
})
export class AppComponent  {

  @HostBinding('style.color') color; 

  @HostListener('click')
  onclick() {
    this.color =  'blue';
  }

}
Run Code Online (Sandbox Code Playgroud)

在上面的示例中,发生以下情况:

  • 将事件侦听器添加到click事件,当组件内任何地方发生click事件时将触发该事件侦听器
  • color我们的物业AppComponent类绑定到style.color组件的财产。因此,每当color属性更新时style.color,组件的属性也会更新
  • 结果是,只要有人单击该组件,颜色就会被更新。

用途@Directive

尽管可以在组件上使用这些装饰器,但通常在属性指令中使用它们。当在中使用时@Directive,主机会更改放置指令的元素。例如看一下这个组件模板:

<p p_Dir>some paragraph</p>
Run Code Online (Sandbox Code Playgroud)

这里p_Dir是<p>元素上的指令。当@HostBinding或者@HostListener被指令类中使用的主机现在参考<p>


Ral*_*kay 6

Jargons较少的理论

@Hostlistnening基本上处理主机元素说(按钮)听用户的动作并执行某个功能说警告("啊!"),而@Hostbinding是另一种方式.在这里,我们在内部监听该按钮上发生的变化(比如单击该类发生的事情时),我们使用该更改来执行其他操作,例如发出特定颜色.

想想你想在一个组件上制作一个喜欢的图标的场景,现在你知道你必须知道该项是否已经被收藏,其类改变了,我们需要一种方法来确定它.这正是@Hostbinding的用武之地.

并且需要知道@Hostlistening进入的用户实际执行了什么操作

  • 这很令人困惑,装饰器名称不准确. (3认同)

roh*_*095 5

方法装饰器:

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

 @HostBinding('class.active')
 activeClass = false;
Run Code Online (Sandbox Code Playgroud)

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

@HostListener('click')
 activeFunction(){
    this.activeClass = !this.activeClass;
 }
Run Code Online (Sandbox Code Playgroud)

宿主元素:

  <button type='button' class="btn btn-primary btn-sm" appHost>Host</button>
Run Code Online (Sandbox Code Playgroud)