我正在尝试创建一个在线商店,但很难实现一个灵活的表单系统,理想情况下,该系统应该根据我添加到商店的项目类型进行更改。例如,当选择“服装”类别时,创建的对象的静态类型会发生变化,表单会自动变形并删除/创建所有必要的输入域。
interface Item {
id: string;
title: string;
category: string;
price: number;
}
interface ClothingItem extends Item {
size: string;
}
interface MonitorItem extends Item {
resolution: string;
}@Component({…})
export class ItemCreateComponent {
item: Item;
form = this.fb.group({
category: [''],
title: [''],
price: [''],
});
constructor(private fb: FormBuilder) { }我期望发生的事情是,当用户在表单中选择“服装”类别时,item的类型会更改为ClothingItem,而form属性会添加缺少的表单控件。
这个问题真的很难表达,我真心希望你至少能明白一点。
发布于 2019-08-08 17:22:11
你可以这样做(这只是一个想法,我还没有测试过它):
@Component({…})
export class ItemCreateComponent {
formFields: string[] = [];
form: FormGroup = new FormGroup();
item: Item;
constructor(private fb: FormBuilder) {}
buildForm(item: Item) {
this.formFields = [];
const obj = {};
const keys = Object.keys(item).sort();
for(const key of keys) {
obj[key] = [''];
}
// The setTimeout is just to give time to angular change
// detection to destroy the form already present on the dom
// before switching to the new form shape. Otherwise,
// you could get an error for having, in the form template,
// HTML form elements different from the ones currently set
// on this.form object
setTimeout(() => {
this.form = this.fb.group(obj);
this.formFields = keys;
}, 300);
}在模板中
<form [formGroup]="form">
<input *ngFor="let field of formFields"
[formControlName]="field">
</form>发布于 2019-07-25 22:34:57
如果您希望您的项目是可互换的,项目的类型应该是any,而不是Item,因为这将只接受Item类型的对象。
如果您想在以后检查您的项目是否具有正确的类型,请使用
item instanceof yourDerivedItem或
const result = (item: any): item is yourDerivedItem => { return true }https://stackoverflow.com/questions/57204053
复制相似问题