Angular 指令的属性和事件绑定

文中使用的工具或者包的版本:Angular CLI 11.0.6

一、实现思路

指令没有模板,需要寄宿在一个元素之上,这个元素我们称之为宿主(Host)。为指令绑定属性和事件实质上是将属性和事件绑定到宿主上。知道了这个之后,实现思路就很明确了——操作宿主元素。推荐使用 Angular 提供的 ElementRefRenderer2 进行访问和操作,举个例子:

// 指令
import { Directive, ElementRef, Input, OnInit, Renderer2 } from '@angular/core';

@Directive({
  selector: '[appHighlightLink]'
})
export class HighlightDirective implements OnInit {
  @Input('appHighlightLink') link: string;
  @Input() color = '#00458b';

  constructor(private elr: ElementRef, private rd2: Renderer2) {
    this.rd2.setStyle(this.elr.nativeElement, 'text-decoration', 'underline');
    this.rd2.setStyle(this.elr.nativeElement, 'cursor', 'pointer');
  }

  ngOnInit(): void {
    this.rd2.setStyle(this.elr.nativeElement, 'color', this.color);
    this.rd2.listen(this.elr.nativeElement, 'click', () => {
      if (this.link) window.open(this.link, '_blank');
    });
  }
}
// 宿主组件
import { Component } from "@angular/core";

@Component({
  selector: 'my-app',
  template: `
    HTTP/1.1 在1997年1月以 <span [appHighlightLink]="link">RFC 2068</span> 文件发布。
  `,
})
export class AppComponent {
  link = 'https://tools.ietf.org/html/rfc2068';
}

这里我们为 appHighlightLink 指令所在的宿主绑定了一些样式和一个点击事件,其中有些属性是用 @Input 装饰器输入的。当然我们也可以使用 @Output 去输出一些属性,虽然这里没有演示。

二、HostBinding 和 HostListener 装饰器

Angular 提供了 HostBindingHostListener 装饰器,专门用来为宿主绑定属性和事件,这可以让代码变得更加简洁。现在我们就来改写一下上面的指令:

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

@Directive({
  selector: '[appHighlightLink]'
})
export class HighlightDirective {
  @HostBinding('style.text-decoration') decoration = 'underline';
  @HostBinding('style.cursor') cursor = 'pointer';
  @HostBinding('style.color') @Input() color = '#00458b';
  @Input('appHighlightLink') link: string;

  @HostListener('click') onClick() {
    if (this.link) window.open(this.link, '_blank');
  }
}

现在我们实现了同样的效果,但比起之前的代码简洁了不少。

原文地址:https://www.cnblogs.com/yshenhua/p/14618766.html