繁体   English   中英

绑定属性值上的 Angular 组件选择器

[英]Angular component selector on a bound attribute value

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

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 解决问题的顺序。 我想要的可能吗?

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

您的指令应将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在模板中使用*ngIf

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

我认为语法上可能有一个小问题。 尝试使用“[selector_name]”。 添加一个链接, 这是一个用于选择器的链接。

属性绑定的语法类似于属性绑定,但不是括号之间的元素属性,而是在属性名称前加上前缀 attr,后跟一个点。 然后,您使用解析为字符串的表达式设置属性值。 https://angular.io/guide/attribute-binding

在你的情况下,应该是这样

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM