5

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.

2 Answers 2

6

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">
Sign up to request clarification or add additional context in comments.

1 Comment

I am going to accept this answer as it was correct even though I ended up using a different solution. Thank you
2

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.