Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular 6 ngFor referencing loop variable in same parent element

Tags:

angular

I have an Angular Material accordion I wish to create using an *ngFor as follows -

<mat-expansion-panel class="noShadow border-top"
                     [expanded]="guest.get('expanded').value"
                     [formGroup]="guest"
                     *ngFor="let guest of guestFormArr.controls; let i = index;">

Please take note of the [expanded] attribute whereby I need to set it according to the 'guest' variable from the *ngFor loop.

I can't seem to get this to work. Is this even possible? Can an element access the 'guest' variable at the same level it is defined? I understand the nested elements accessing 'guest'.

Thank you

SOLUTION:

I ended up doing the following

<mat-expansion-panel class="noShadow border-top"
                 *ngFor="let guest of guestFormArr.controls; let i = index;"
                 [formGroup]="guest" [expanded]="open === i">

I would then simply increase or decrease the 'open' variable on the 'Next' and 'Back' buttons which had (click)=next(i) or (click)=back(i) respectively.

like image 488
Koman Avatar asked Mar 05 '23 08:03

Koman


2 Answers

Order matters, set expanded and formGroup property after the *ngFor. Currently, you are trying to set those properties before initializing guest variable so it will be undefined.

<mat-expansion-panel class="noShadow border-top"
                     *ngFor="let guest of guestFormArr.controls; let i = index;"
                     [formGroup]="guest"
                     [expanded]="guest.get('expanded').value">
like image 117
Pranav C Balan Avatar answered May 05 '23 21:05

Pranav C Balan


The problem here is that you are using guest before you declare it. To fix it just change the order of attributes it should work then.

Put the *ngFor before all attribute that uses guest.

<mat-expansion-panel class="noShadow border-top"
                     *ngFor="let guest of guestFormArr.controls; let i = index;"
                     [expanded]="guest.get('expanded').value"
                     [formGroup]="guest">
like image 23
Josef Katič Avatar answered May 05 '23 22:05

Josef Katič