1

[(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[];
    });
  }
N.F.
  • 3,844
  • 3
  • 22
  • 53
  • what data are you get in parameters.account.roles and allRoles? – Jayrag Pareek Nov 29 '21 at 06:06
  • parameters.account.roles is a list of objects Role that has been applied to the user. [{id: 'ROLE202111001', name: 'ROLE_ADMIN'}]. And all roles is the same, but a list of all registered roles in role table. @jayrag pareek – Daniel Matute Nov 29 '21 at 06:11
  • both array object are using same model Role? – Jayrag Pareek Nov 29 '21 at 06:15
  • Yes, UserAccount has an attribute called roles: Role[] and when I fetch all roles I use as Role[]. this.allRoles = response._embedded.roleList as Role[]. this.allRoles is of type Role[]. – Daniel Matute Nov 29 '21 at 06:20

1 Answers1

1

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>
Jayrag Pareek
  • 354
  • 3
  • 15