Not able to select the default value into mat-select with optgroup grouping data

302 Views Asked by At

I need help for selecting the default data which is coming from api side into the mat-select optgroup form.

The details are given below:

<mat-form-field class="col-md-12 mt-top25">
              <mat-label>Department</mat-label>
              <mat-select formControlName="department" multiple (selectionChange)="getDepartment()" [compareWith]="compareWith">
                <mat-optgroup *ngFor="let group of departmentList" [label]="group.group"
                  [disabled]="group.disabled">
                  <mat-option *ngFor="let data of group.names" [value]="data">
                    {{data.department}}
                  </mat-option>
                </mat-optgroup>
              </mat-select>
            </mat-form-field>

this is the html part of the department page:

[
  {
    "group": "Kuala Lumpur",
    "names": [
      {
        "id": 1,
        "department": "EMERGENCY ROOM",
        "facilityCode": "KLAN",
        "facilityName": "Kuala Lumpur"
      },
      {
        "id": 2,
        "department": "FINANCE & ADMIN",
        "facilityCode": "KLAN",
        "facilityName": "Kuala Lumpur"
      },
      {
        "id": 3,
        "department": "OUTPATIENT DEPARTMENT",
        "facilityCode": "KLAN",
        "facilityName": "Kuala Lumpur"
      },
      {
        "id": 4,
        "department": "PHARMACY ",
        "facilityCode": "KLAN",
        "facilityName": "Kuala Lumpur"
      },
      {
        "id": 5,
        "department": "MULTIDISCIPLINE 1",
        "facilityCode": "KLAN",
        "facilityName": "Kuala Lumpur"
      }
    ]
  }
]

This is the departmentList data which is currently showing into the dropdown of he mat-select.

The data which is I am getting from the dropdown fomrcontrolname = 'deparetment' is:

[
  {
    "department": "FINANCE & ADMIN",
    "facilityCode": "KLAN",
    "facilityName": "Kuala Lumpur",
    "id": 2
  },
  {
    "department": "OUTPATIENT DEPARTMENT",
    "facilityCode": "KLAN",
    "facilityName": "Kuala Lumpur",
    "id": 3
  }
]

But when I am running the form value is not selected into the same.

I am also setting the value directly into the form control name:

this.f['department'].setValue([ { "id": 2, "department": "FINANCE & ADMIN", "facilityCode": "KLAN", "facilityName": "Kuala Lumpur" }, { "id": 3, "department": "OUTPATIENT DEPARTMENT", "facilityCode": "KLAN", "facilityName": "Kuala Lumpur" } ] );

I am not sure about the compareWith function because its also not working in this case.

Attached image is here.

enter image description here

0

There are 0 best solutions below