在我漫游的世界各地互联网,现在尤其是角。我发现很多@HostBinding和@HostListener的引用。它们似乎是相当基本的,但不幸的是,目前它们的文档有点粗略。
谁能解释一下它们是什么,它们是如何工作的,并举例说明它们的用法吗?
在我漫游的世界各地互联网,现在尤其是角。我发现很多@HostBinding和@HostListener的引用。它们似乎是相当基本的,但不幸的是,目前它们的文档有点粗略。
谁能解释一下它们是什么,它们是如何工作的,并举例说明它们的用法吗?
当前回答
少些行话的理论
@Hostlistnening主要处理的是主机元素,比如(一个按钮)监听用户的操作,并执行某个功能,比如警报(“Ahoy!”),而@Hostbinding则相反。在这里,我们侦听在该按钮上发生的内部更改(例如当它被单击时,类发生了什么),我们使用该更改来做其他事情,例如发出特定的颜色。
例子
想象一下这样的场景,你想在一个组件上创建一个收藏图标,现在你知道你必须知道这个项目是否随着类的改变而被收藏,我们需要一种方法来确定这一点。这正是@Hostbinding的用武之地。
如果需要知道用户实际执行了什么操作,就需要使用@Hostlistening
其他回答
方法修饰符:
@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>
少些行话的理论
@Hostlistnening主要处理的是主机元素,比如(一个按钮)监听用户的操作,并执行某个功能,比如警报(“Ahoy!”),而@Hostbinding则相反。在这里,我们侦听在该按钮上发生的内部更改(例如当它被单击时,类发生了什么),我们使用该更改来做其他事情,例如发出特定的颜色。
例子
想象一下这样的场景,你想在一个组件上创建一个收藏图标,现在你知道你必须知道这个项目是否随着类的改变而被收藏,我们需要一种方法来确定这一点。这正是@Hostbinding的用武之地。
如果需要知道用户实际执行了什么操作,就需要使用@Hostlistening
下面是一个基本的悬停例子。
组件的模板属性:
模板
<!-- 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" ;
}
}
有一件事使这个主题更加混乱,那就是装饰者的概念不是很清楚,当我们考虑像……
@HostBinding('attr.something')
get something() {
return this.somethingElse;
}
它可以工作,因为它是一个get访问器。你不能使用等价的函数:
@HostBinding('attr.something')
something() {
return this.somethingElse;
}
否则,使用@HostBinding的好处是它确保在绑定值发生变化时运行更改检测。
@HostBinding的另一个好处是,如果你的绑定直接依赖于一个输入,你可以将它与@Input结合起来,例如:
@HostBinding('class.fixed-thing')
@Input()
fixed: boolean;