user3471528
user3471528

Reputation: 3053

Declare variable in ngFor

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>
        ...

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?

Thanks a lot

Upvotes: 3

Views: 3652

Answers (1)

G&#252;nter Z&#246;chbauer
G&#252;nter Z&#246;chbauer

Reputation: 657068

You currently can't assign arbitrary values to template variables.

  • 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 by ngFor 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.

As a workaround you might consider wrapping a part of your template into its own component and pass values to @Input()s

Upvotes: 4

Related Questions