Вы проверили эти официальные документы?
HostListener - объявляет слушателя хоста. Angular вызовет декорированный метод, когда элемент хоста испускает указанное событие.
@HostListener
- будет прослушивать событие, генерируемое элементом хоста, объявленным с помощью @HostListener
.
HostBinding - объявляет привязку свойства хоста. Angular автоматически проверяет привязки свойств хоста во время обнаружения изменений. Если привязка изменится, она обновит хост-элемент директивы.
@HostBinding
- привяжет свойство к элементу хоста. Если привязка изменится, HostBinding
обновит элемент хоста.
ПРИМЕЧАНИЕ. Обе ссылки недавно были удалены. Часть руководства по стилю "HostBinding-HostListening" может быть полезная альтернатива, пока ссылки не вернутся.
Вот простой пример кода, который помогает понять, что это означает:
ДЕМО: Вот демонстрация в плункере - «Простой пример о @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>
становится <p mydir="" role="admin">
, когда вы просматриваете его в инструментах разработчика.
- 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 {}
person
micronyks
schedule
22.06.2016