Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Declare variable in ngFor

Tags:

angular

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

like image 608
user3471528 Avatar asked Aug 16 '26 05:08

user3471528


1 Answers

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

like image 146
Günter Zöchbauer Avatar answered Aug 17 '26 18:08

Günter Zöchbauer



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!