the options are not showing or being selected in mat-select

Viewed 11318

I want to preselect some options inside mat-select field in my Angular Form, so I have this code in typescript file:

selectedApps = [];
ngOnInit() {
    const url = this.baseUrl + `/projects/${this.id}`;
    this.httpClient.get(url).subscribe((data: Array<any>) => {
        for (let i=0; i<data['results'][0]['apps'].length; i++) {
            this.selectedApps.push(data['results'][0]['apps'][i]['name']);    
        }

    });
}

Here is the mat-select input fild:

          <div class="col-sm-8 float-left">

        <mat-form-field> <mat-select
          [(value)]="selectedApps" 
          placeholder="Select the associated applications ..."
          multiple (click)="getAppList();"> <mat-option
          *ngFor="let app of appsList?.results" [value]="app.id">{{app.name
        }}</mat-option> </mat-select> </mat-form-field>
      </div>

My problem is that the value of selectedApps does not show inside the field, even that the values are properly pushed inside the array. why is that?

4 Answers

You are "preselecting" names

this.selectedApps.push(data['results'][0]['apps'][i]['name']);  

while your options contains ids

<mat-option
          *ngFor="let app of appsList?.results" [value]="app.id">{{app.name
        }}</mat-option>

In order to get it work, selectedApps mush keep the same values that are available on mat-option [value] property. After all, this is what will be the actual mat-select value.

To be honest, I would make whole app as a value as there is no reason to threat it orherwise. It would simplify much of code.

I added some dummy data in the component.ts file and I can see the selectedApps in the form field.

in the template file

<form>
  <div class="col-sm-8 float-left">
    <mat-form-field> <mat-select
      [(value)]="selectedApps" 
      placeholder="Select the associated applications ..."
      multiple (click)="getAppList();"> <mat-option
      *ngFor="let app of appsList" [value]="app.value">{{app.name
    }}</mat-option> </mat-select> </mat-form-field>
  </div>

and in the ts file:

export class SelectFormExample {
selectedApps: string;
 appsList = [
 {value: 'app_1', results: 'App1-result', name: 'APP 1'},
{value: 'app_2', results: 'App2-result', name: 'APP 2'},
{value: 'app_3', results: 'App3-result', name: 'APP 3'}
];

getAppList(){
    console.log('getAppList');
  }

It's because of conflicting z-indexes. Are you render mat-select inside kind of a pop-up modal?

Hope this work:

Put this style in your global style sheet called styles.css or .scss

 .cdk-global-overlay-wrapper, .cdk-overlay-container {
     z-index: 99999 !important;
  }

I checked the dom and the mat-option exist but its not shown i fixed it on css

::ng-deep {
  div#mat-select-2-panel {
    height: auto;
    background: white !important;
  }
}

Related