我使用 react 形式和 Angular Material 创建了一个表单 垫子选择 我用它来创建一个名为“ 核心”的对象。核心对象有两个属性:“name”和“owners”。 “owners”属性是一个数组 用户 对象。
核心对象:
export interface ICore {
id?: number;
name: string;
owners: IUser[];
}
表格:
<form [formGroup]="parentForm">
<mat-form-field class="example-full-width">
<input matInput formControlName="name" placeholder="Name">
</mat-form-field>
<mat-form-field class="example-full-width">
<mat-label>Users</mat-label>
<mat-select formControlName="owners" multiple>
<mat-option *ngFor="let user of users" [value]="user"> {{ user.username }}</mat-option>
</mat-select>
</mat-form-field>
</form>
“ users ”变量是可以选择的所有可用用户的数组。
users: IUser[];
该表单效果很好,但现在我想使用相同的表单来编辑核心对象,为此我需要在加载页面时在“所有者”表单控件中显示核心所有者。
表单创建:
createForm() {
this.coreForm = this.formBuilder.group({
name: ['', [Validators.required]],
owners: ['', [Validators.required]]
});
}
我如何获得核心:
getCore() {
this.coreService.getCore(this.route.snapshot.params['id'])
.subscribe(
res => {
this.core = res;
this.updateForm();
},
err => this.toastr.error('Core has not been received!', 'Error!')
);
}
表单更新(适用于 name 属性):
updateForm() {
this.coreForm.patchValue({
name: this.core.name,
owners: this.core.owners
});
}
但是没有添加所有者列表。奇怪的是,如果我用 更新表单用户 有用:
getUsers() {
this.usersService.getUsers()
.subscribe(
res => {
this.users = res;
this.coreForm.patchValue({
owners: res
});
},
err => this.toastr.error('User could not be received!', 'Error!')
);
}
这样所有用户都被添加为默认值。但对于核心所有者来说,它不起作用。知道我在这里做错了什么吗?
提前致谢!
最佳答案
您需要使用 [compareWith]
定义将对象视为选定对象的标准。指令如下:
<form [formGroup]="parentForm">
<mat-form-field class="example-full-width">
<input matInput formControlName="name" placeholder="Name">
</mat-form-field>
<mat-form-field class="example-full-width">
<mat-label>Users</mat-label>
<mat-select [compareWith]="compareFunction" formControlName="owners" multiple>
<mat-option *ngFor="let user of users" [value]="user"> {{ user.username }}</mat-option>
</mat-select>
</mat-form-field>
</form>
并定义您的 compareFunction:
compareFunction(o1: any, o2: any) {
return (o1.name == o2.name && o1.id == o2.id);
}
关于 Angular Material : mat-select default value when using reactive forms,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56187371/