如何从类创建映射以提取其属性作为值?

问题描述 投票:0回答:3

我想在 Angular 模板和 FormGroup 之间创建更强大的类型安全链接。我想到了以下内容,但我不知道如何在 TypeScript 中正确表达它。

我想用一个对象来设置 FormGroup

controls
对象的 keys
FormControl
构造函数的第一个参数),以及
formControlName
中的绑定模板,从模型类开始。

我的理由是,这将删除因使用字符串作为 formControlName 属性而产生的“字符串”或所谓的

magic string
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('')
  });
}

谢谢!

angular typescript angular-reactive-forms type-safety
3个回答
2
投票

我似乎找到了一种方法。

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
(表单控件名称)变量,只是为了在模板中绑定表单控件的正确名称?如果可能的话,我很想消除它的重复代码。


0
投票

这可能有点晚了,但看起来您可以简单地使用像这样的

setValue
方法来完成此操作。
this.formGroup.setValue(this.preFilledData)


-1
投票

这是避免所谓的

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;
}
© www.soinside.com 2019 - 2024. All rights reserved.