[英]How can I set a template variable reference on the first item of a list in Angular2?
我想在列表的第一项上设置模板变量引用。 这是我的代码(不起作用):
<li *ngFor="let favorite of favorites; let first= first">
<template [ngIf]="first" #firstitem>
{{ favorite.name }}
</template>
<template [ngIf]="!first">
{{ favorite.name }}
</template>
</li>
如果我删除ngFor
这就是我想做的事情:
<ul>
<li #firstitem>
some content
</li>
<li>
other content
</li>
</ul
有人知道如何实现吗?
没有办法有条件地添加或不添加模板变量。
你能做的就是使用
@ViewChilderen('firstitem') items:QueryList<ElementRef>;
firstItem:ElementRef;
ngAfterViewInit() {
var items = this.items.toArray();
if(items.length) {
this.firstItem = items[0];
}
}
然后可以将firstItem
用于模板中的绑定。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.