Listening to an Element Host

Listening to the host - that is, the DOM element the directive is attached to - is among the primary ways directives extend the component or element's behavior. Previously, we saw its common use case.

  1. @Directive({
  2. selector: '[appMyDirective]'
  3. })
  4. class MyDirective {
  5. @HostListener('click', ['$event'])
  6. onClick() {}
  7. }

We can also respond to external events, such as from window or document, by adding the target in the listener.

  1. @Directive({
  2. selector: `[appHighlight]`
  3. })
  4. export class HighlightDirective {
  5. constructor(private el: ElementRef, private renderer: Renderer) { }
  6. @HostListener('document:click', ['$event'])
  7. handleClick(event: Event) {
  8. if (this.el.nativeElement.contains(event.target)) {
  9. this.highlight('yellow');
  10. } else {
  11. this.highlight(null);
  12. }
  13. }
  14. highlight(color) {
  15. this.renderer.setElementStyle(this.el.nativeElement, 'backgroundColor', color);
  16. }
  17. }

View Example

Although less common, we can also use @HostListener if we'd like to register listeners on the host element of a Component.

Host Elements

The concept of a host element applies to both directives and components.

For a directive, the concept is fairly straight forward. Whichever template tag you place your directive attribute on is considered the host element. If we were implementing the HighlightDirective above like so:

  1. <div>
  2. <p appHighlight>
  3. <span>Text to be highlighted</span>
  4. </p>
  5. </div>

The <p> tag would be considered the host element. If we were using a custom TextBoxComponent as the host, the code would look like this:

  1. <div>
  2. <app-my-text-box appHighlight>
  3. <span>Text to be highlighted</span>
  4. </app-my-text-box>
  5. </div>

In the context of a Component, the host element is the tag that you create through the selector string in the component configuration. For the TextBoxComponent in the example above, the host element in the context of the component class would be the <app-my-text-box> tag.

原文: https://angular-2-training-book.rangle.io/handout/advanced-angular/directives/listening_to_an_element_host.html