如何解决如何从类创建映射以将其属性提取为值?
我想在 Angular 模板和 FormGroup 之间创建一个更强大的类型安全链接。我想到了以下,但我不知道如何在 TypeScript 中正确表达。
我想使用一个对象来设置 FormGroup 的 controls
对象的键(FormControl
构造函数的第一个参数)、以及模板中formControlName
的绑定,从模型类开始。
我的理由是,这将删除因使用字符串作为 formControlName
属性而产生的“字符串”或所谓的魔法字符串 API。这样,唯一的事实来源就是模型类。这也让我可以轻松重构该类并更新所有其他引用。
例如,我希望能够写出这样的东西:
// model class:
class Partner {
id: string;
name: string;
}
// some static type SomeType = { id: "id",name: "name" } extends Partner's public properties
// but the values of those properties must equal the property name.
// component:
@Component({
template: `
<form [formGroup]="form" (ngSubmit)="onSubmit()" novalidate>
<!-- notice I'm not using a stringy API like formControlName="id" -->
<input type="text" [formControlName]="SomeType.id">
<input type="text" [formControlName]="SomeType.name">
</form>
`})
class CreatePartnerComponent {
form = new FormGroup({
SomeType.id: new FormControl(''),SomeType.name: new FormControl('')
});
}
谢谢!
解决方法
我似乎找到了一种(一种)方法。
class ModelClass {
id: string;
name: string;
}
// for the template I need a literal object that I can access by key
// and provide form control names as strings to bind the formControlName
// directive to,so I declare this inside the component class:
readonly fcName: { [key in keyof ModelClass]: key } = {
// the problem with this is you need to explicitly declare the properties here and
// keep this property up to date when you refactor ModelClass,but you still
// get an error if you forget to,so that's great.
// Also some IDEs can auto-fill these properties along with the values as well.
id: 'id',name: 'name'
}
// and bind form controls like [formControlName]="fcName.id" and so on,// in the template,this should be pretty obvious by now.
// and the form group you now declare like this,which
// enforces correct key names based on the model:
form = new FormGroup({
id: new FormControl(''),name: new FormControl('')
} as { [key in keyof ModelClass]: FormControl });
任何其他更优雅的方式来做到这一点,也许不需要创建 fcNames
(表单控件名称)变量,只是为了绑定模板中表单控件的正确名称?如果可能的话,我很想消除它的重复代码。
这是避免所谓的 magic string
的一个非常好的做法。可能的解决方案可能是:
class ModelClass {
id: string;
age: number;
}
class MyFormGroup extends FormGroup {
controls: {
[key in keyof ModelClass]: AbstractControl;
};
}
@Component({
template: `
<form [formGroup]="form"
(ngSubmit)="onSubmit()"
novalidate>
<input type="text"
[formControl]="form.controls.id" />
<input type="text"
[formControlName]="form.controls.age" />
</form>
`,})
class CreatePartnerComponent {
someEnum = MyFormGroup; // trick to use enum inside the template
formConfig: { [key in keyof ModelClass]: FormControl } = {
id: new FormControl(),age: new FormControl(),};
form = new FormGroup(this.formConfig) as MyFormGroup;
}
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。