在创建 angular 指令时使用 Input

Use of Input in creation of angular directive

以下是 Angular 属性指令文档中给出的指令示例 https://angular.io/guide/attribute-directives

import { Directive, ElementRef, Input } from '@angular/core';
@Directive({ selector: '[myHighlight]' })
export class HighlightDirective {
    constructor(el: ElementRef) {
       el.nativeElement.style.backgroundColor = 'yellow';
    }
}

就在它下面,他们用下面的文字解释了它

  1. 导入语句指定来自 Angular 核心的符号:
  2. Directive 提供@Directive 装饰器的功能。
  3. ElementRef 注入指令的构造函数,因此代码可以访问 DOM 元素。
  4. 输入允许数据从绑定表达式流入指令。

第四点我不清楚,他们说输入允许数据从绑定表达式流入指令,但是在class没有使用输入的地方,那怎么可能Angular使用它,因为之前我读过 NgModule 文档,上面的 import 语句与 Angular

无关

所以我的理解是每当Angular遇到属性指令时,它会使用class HighlightDirective创建一个对象,但由于它没有任何对Input的引用,它如何获取数据来自绑定表达式的流

所以据我了解,因为我们不在此处访问数据,所以我们不需要在顶部导入输入模块

你不需要为这个指令使用Input,因为它被放置在一个元素上,我们通过将指令放在元素之上然后直接修改元素来获取元素的所有属性颜色 .

But once you need to pass a value to the directive you will need to use the @Input . like for eg passing the background color dynamically on the go.

查看输入导入的工作示例LINK

HighlightDirective 指令没有 @Input()

如果您查看 *ngIf 指令的来源,它应该会变得更加清晰

@Directive({selector: '[ngIf]'})
export class NgIf {
  ...

  constructor(private _viewContainer: ViewContainerRef, templateRef: TemplateRef<NgIfContext>) {
    this._thenTemplateRef = templateRef;
  }

  @Input()
  set ngIf(condition: any) {
    this._context.$implicit = this._context.ngIf = condition;
    this._updateView();
  }

该指令确实有一个输入,我假设您熟悉它的用法

<div *ngIf="isVisible"

其中 isVisible 的值被传递给 @Input() ngIf;(在本例中为 setter,但我将其关闭,因为通常它只是一个字段,而不是 setter)