【发布时间】:2019-10-04 20:13:20
【问题描述】:
我使用反应形式和角度材料 mat-select 创建了一个表单,我用它来创建一个名为“core”的对象。核心对象有 2 个属性:“名称”和“所有者”。 “owners”属性是 IUser 对象的数组。
核心对象:
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
});
}
但没有添加所有者列表。奇怪的是,如果我用 users 更新表单,它会起作用:
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]="defineYourCompareFunction" 添加到您的 mat-select 中?
-
@ala,不。我不知道这个属性
-
compareFunction(o1: any, o2: any) { if(o1.name == o2.name && o1.id == o2.id ) return true; else return false } -
这是一个比较函数的例子,试试看告诉我
-
来自文档:/** 将选项值与选定值进行比较的函数。第一个参数是来自选项的值。第二个是来自选择的值。应该返回一个布尔值。 **/
标签: angular angular-material angular7 reactive-forms