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 解决问题的顺序。我想要的可能吗?
我认为语法上可能存在一些小问题。尝试使用“[selector_name]”。添加 link、this one 以供选择器使用。
属性绑定语法类似于 属性 绑定,但不是方括号之间的元素 属性,而是在属性名称前面加上前缀 attr,后跟一个点。然后,您使用解析为字符串的表达式设置属性值。 https://angular.io/guide/attribute-binding
你的情况应该是这样
<div *ngFor="let item of items">
<div [attr.data-type]="item.type"></div>
</div>
无法根据更改检测添加或删除指令。该指令要么始终存在,要么不存在。
您的指令应将 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
:
<div *ngIf="dataType === 'Type1'">
<!-- the component's body -->
</div>
我正在尝试对属性值的组件选择器进行编码,如下所示:
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 解决问题的顺序。我想要的可能吗?
我认为语法上可能存在一些小问题。尝试使用“[selector_name]”。添加 link、this one 以供选择器使用。
属性绑定语法类似于 属性 绑定,但不是方括号之间的元素 属性,而是在属性名称前面加上前缀 attr,后跟一个点。然后,您使用解析为字符串的表达式设置属性值。 https://angular.io/guide/attribute-binding
你的情况应该是这样
<div *ngFor="let item of items">
<div [attr.data-type]="item.type"></div>
</div>
无法根据更改检测添加或删除指令。该指令要么始终存在,要么不存在。
您的指令应将 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
:
<div *ngIf="dataType === 'Type1'">
<!-- the component's body -->
</div>