Home > Software engineering >  Data binding becomes undefined when ngif is added to mat-selection-list
Data binding becomes undefined when ngif is added to mat-selection-list

Time:04-20

I am displaying a mat-selection-list based on some condition. The issue is that after I added the ngif condition, the data is always being set to undefined. I can't seem to figure out what's the issue. Thanks in advance for your help:

My template:

<mat-card  *ngIf="!loading">
            <mat-card-header>
                <mat-card-title ><u>Events</u></mat-card-title>
            </mat-card-header>
            <mat-selection-list #event>
                <mat-list-option *ngFor="let event of listOfEvents" [value]="event.value" [selected]="event.selected" >
                    {{event.name}}
                </mat-list-option>
            </mat-selection-list>
        </mat-card>
        
                <button  (click)="save(event)"  type="button" >Save</button>

My ts code:

            save(events: any): void {
    console.log(events); //coming as undefined
  }

CodePudding user response:

To stay initializable the Material selection list need to exist / be defined. You can use [hidden] or your own css class with "display:none" so material select list can initialize the buttons in the background.

[hidden]="loading" instead of *ngIf="!loading"

CodePudding user response:

You should use ViewChild

 @ViewChild('event') event;
  • Related