How to use [(ngModel)] in a multiple select to select the options stored in the database?

Issue

[(ngModel)]="parameters.account.roles" contains the selected options as those are obtained from the database, but no option is selected when I open the dialog.

All other fields show the correct data and parameters.account.roles is not empty.

HTML

<mat-form-field appearance="fill">
     <mat-label>Role</mat-label>
     <mat-select multiple [(ngModel)]="parameters.account.roles">
        <mat-option *ngFor="let role of allRoles" [value]="role">{{role.name}}</mat-option>
     </mat-select>
</mat-form-field>

TS

  constructor(
    public dialogRef: MatDialogRef<UserAccountFormComponent>,
    @Inject(MAT_DIALOG_DATA) public parameters: {mode: ActionMode, account: UserAccount},
    private roles:RolesService) {
       this.account = parameters.account;
  }

  ngOnInit(): void {
    this.roles.getAll().subscribe((response: any) => {
      this.allRoles = response._embedded.roleList as Role[];
    });
  }

Solution

Try this:

In ts file:

compareFn(role1: Role, role2: Role) {
    return role1 && role2 ? role1.id === role2.id : role1 === role2;
}

and HTML File:

<mat-form-field appearance="fill">
     <mat-label>Role</mat-label>
     <mat-select multiple [compareWith]="compareFn" [(ngModel)]="parameters.account.roles">
        <mat-option *ngFor="let role of allRoles" [value]="role">{{role.name}}</mat-option>
     </mat-select>
</mat-form-field>

Answered By – Jayrag Pareek

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published