如何使用[(ngModel)]中的多个select到select选项存储在数据库中?
How to use [(ngModel)] in a multiple select to select the options stored in the database?
[(ngModel)]="parameters.account.roles"
包含从数据库中获取的选定选项,但是当我打开对话框时没有选择任何选项。
所有其他字段显示正确的数据并且 parameters.account.roles
不为空。
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[];
});
}
试试这个:
在ts文件中:
compareFn(role1: Role, role2: Role) {
return role1 && role2 ? role1.id === role2.id : role1 === role2;
}
和HTML文件:
<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>
[(ngModel)]="parameters.account.roles"
包含从数据库中获取的选定选项,但是当我打开对话框时没有选择任何选项。
所有其他字段显示正确的数据并且 parameters.account.roles
不为空。
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[];
});
}
试试这个:
在ts文件中:
compareFn(role1: Role, role2: Role) {
return role1 && role2 ? role1.id === role2.id : role1 === role2;
}
和HTML文件:
<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>