我认为局部变量(使用 # 字符定义)不适用于您的用例。
事实上,当您在 HTML 元素上定义局部变量时,它对应于组件(如果有)。当元素上没有组件时,变量引用元素本身。
为局部变量指定值允许您选择与当前元素关联的特定指令。例如:
<input #name="ngForm" ngControl="name" [(ngModel)]="company.name"/>
将在name 变量中设置与当前关联的ngForm 指令的实例。
因此,局部变量并不针对您想要的,即设置为循环的当前元素创建的值。
如果你尝试这样做:
<div *ngFor="#elt of eltList" >
<span #localVariable="elt.title"></span>
{{localVariable}}
</div>
您将遇到以下错误:
Error: Template parse errors:
There is no directive with "exportAs" set to "elt.title" ("
<div *ngFor="#elt of eltList" >
<span [ERROR ->]#localVariable="elt.title"></span>
{{localVariable}}
</div>
"): AppComponent@2:10
Angular2 实际上会在此处查找与提供的名称 elt.title 匹配的指令)...查看此 plunkr 以重现错误:https://plnkr.co/edit/qcMGr9FS7yQD8LbX18uY?p=preview
有关详细信息,请参阅此链接:http://victorsavkin.com/post/119943127151/angular-2-template-syntax,“局部变量”部分。
除了迭代的当前元素之外,ngFor 只提供了一组导出值,这些值可以别名为局部变量:index、last、even 和 odd。
查看此链接:https://angular.io/docs/ts/latest/api/common/NgFor-directive.html
你可以做的是创建一个子组件来显示循环中的元素。它将接受当前元素作为参数并创建您的“局部变量”作为组件的属性。然后,您将能够在组件的模板中使用此属性,以便循环中的每个元素创建一次。这是一个示例:
@Component({
selector: 'elt',
template: `
<div>{{attr}}</div>
`
})
export class ElementComponent {
@Input() element;
constructor() {
// Your old "localVariable"
this.attr = createAttribute(element.title);
}
createAttribute(_title:string) {
// Do some processing
return somethingFromTitle;
}
}
以及使用方法:
<div *ngFor="#elt of eltList" >
<elt [element]="elt></elt>
</div>