在ngFor中声明变量 [英] Declare variable in ngFor
问题描述
在我的angular2项目中,我需要呈现一个矩阵. 这是我当前的代码:
in my angular2 project I need to present a matrix. This is my current code:
<tr *ngFor="let worker of workers">
<td class="{{worker.fired ? 'fired-worker':''}}">{{worker.lastName}}<br>{{worker.firstName}}</td>
<td *ngFor="let course of courses;" class="sk-table-sub-header">
<div *ngIf="course.isGeneric">
<div class="col-xs-6" sc-dc [sc-dc-date]="matrix[worker.id][course.id].expiration">
<date-picker (onDateChanged)="onDateChanged($event, worker, course, 'genericStartDate')" [date]="matrix[worker.id][course.id].genericStartDate></date-picker>
</div>
<div class="col-xs-6 training-table-rounded-cell" sc-dc [sc-dc-date]="matrix[worker.id][course.id].expiration">
<date-picker (onDateChanged)="onDateChanged($event, worker, course, 'expiration')" [date]="matrix[worker.id][course.id].expiration" ></date-picker>
</div>
</div>
...
如您所见,我多次使用matrix[worker.id][course.id].expiration
.
我尽量避免这样声明变量:
As you can see I use matrix[worker.id][course.id].expiration
multiple times.
I try to avoid that declaring a variable like this:
<td *ngFor="let course of courses; let item = matrix[worker.id][course.id]" ...>
但是我收到一个解析错误:
But I get a parse error:
Parser Error: Unexpected token [, expected identifier, keyword, or string at column 44 in [ngFor let course of courses; let i = matrix[worker.id][course.id]] in TrainingPlanComponent@44:20 ("r.fired ? 'fired-worker':''}}">{{worker.lastName}}<br>{{worker.firstName}}</td>
有没有办法实现我的意图?
Is there a way to achieve my intent?
非常感谢
推荐答案
您目前无法将任意值分配给模板变量.
You currently can't assign arbitrary values to template variables.
- 模板变量可以引用添加了元素或组件的元素 可以将
-
exportAs
引用分配给像#xxx="ngForm"
这样的模板变量
可以分配 - 由
index
或ngFor
等指令创建的局部变量
- template variables can refer to elements or components where they are added
exportAs
references can be assigned to template variables like#xxx="ngForm"
- local variables created by directives like
index
byngFor
can be assigned
还有一个尚待解决的支持您的用例的问题,但尚不清楚是否以及何时支持.
There is an open issue to support your use case as well but it's unclear if and when this will be supported.
作为解决方法,您可以考虑将模板的一部分包装到其自己的组件中,然后将值传递给@Input()
s
As a workaround you might consider wrapping a part of your template into its own component and pass values to @Input()
s
这篇关于在ngFor中声明变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!