我正在尝试显示基于类数组的模板。我不确定我会如何做这样的事情。
我创建了两个将由 for 循环引用的模板。该模板看起来像这样:
<ul>
<li *ngFor="let item of items">
<!-- Show one of the templates here -->
</li>
</ul>
<ng-template #buttonTemplate>
<button>Some Text</button>
</ng-template>
<ng-template #linkTemplate>
<a href="">Some Text</a>
</ng-template>
接下来我创建了一个如下所示的 JavaScript 组件:
@Component({ /* Options */ })
export class MyComponent {
constructor() {
this.items = [
new ButtonClass(),
new LinkClass(),
new ButtonClass()
]
}
}
现在,当项目是 instanceof ButtonClass
时,我将如何使用 #buttonTemplate
,而当项目是 instanceof 时,我将如何使用
?#linkTemplate
链接类
最佳答案
您可以使用*ngIf then else
<ul>
<li *ngFor="let item of items">
<ng-container *ngIf="item instanceOf LinkClass; then buttonTemplate else linkTemplate"></ng-container>
</li>
</ul>
<ng-template #buttonTemplate>
<button>Some Text</button>
</ng-template>
<ng-template #linkTemplate>
<a href="">Some Text</a>
</ng-template>
使用 2 个以上模板:
<ul>
<li *ngFor="let item of items">
<ng-container *ngIf="item instanceOf XXX; then template1"></ng-container>
<ng-container *ngIf="item instanceOf XXX; then template2"></ng-container>
<ng-container *ngIf="item instanceOf XXX; then template3"></ng-container>
<ng-container *ngIf="item instanceOf XXX; then template4"></ng-container>
</li>
</ul>
要将数据传递到模板,您需要执行以下操作:
<ng-container [ngTemplateOutletContext]="{myData:item}"
[ngTemplateOutlet]="item instanceOf XXX ? template_A: null"></ng-container>
和
<ng-template #template_A let-myData='myData'>
{{ myData.name }}
</ng-template>
编辑:您不能在 HTML 中使用实例
。所以你至少有两种选择:
- 使用函数来断言类相等性:
*ngIf="isInstanceOfXXX(item); then X else X"
与
isInstanceOfXXX(item:any): item is ClassX{
return item instance of ClassX;
}
- 映射您的项目以添加一个包含类名称的新字段,例如:
items = items.map(item => ({...item,type: item.constructor.name}))
在你的html中:
*ngIf="item.type === 'ClassX'; then X else X"
但要小心最后一个方法,ClassX.name 是 ES6 功能,因此它在 IE11 中不起作用
关于javascript - 使用基于类实例类型的模板,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58718165/