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

Time:11-30

[(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[];
    });
  }

CodePudding user response:

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>
  • Related