首页 > 解决方案 > 绑定属性值上的 Angular 组件选择器

问题描述

我正在尝试在属性值上编写组件选择器,如下所示:

selector: '[data-type=Type1]'

这在以下 HTML 中效果很好:

<div *ngFor="let item of items">
  <div data-type="Type1"></div>
</div>

但不能这样工作(这当然是我想要的):

<div *ngFor="let item of items">
  <div [data-type]="item.type"></div>
</div>

我猜这是由于 Angular 解决问题的顺序。我想要的可能吗?

标签: angularcomponentsselector

解决方案


不能根据变更检测添加或删除指令。该指令要么始终存在,要么不存在。

您的指令应将值作为输入data-type,然后确定是否执行其工作。

例如

@Directive({
  selector: '[data-type]'
})
export class DataTypeDirective {
  @Input('data-type') dataType: string;

  doSomeStuff() {
    if (this.dataType !== 'Type1') {
      return;
    }
    // perform the directive's function
  }
}

或者,如果它是一个组件,*ngIf请在模板中使用 an:

<div *ngIf="dataType === 'Type1'">
  <!-- the component's body -->
</div>

推荐阅读