Angular 中的强类型表单值

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

如何将表单和底层模型类型绑定在一起?

给定

interface IUser {
  name: string,
  age: number
}

如何生成:

form = new FormGroup<???>({
  name: new FormControl<string>(..)
  age: new FormControl<number>(...)
});

并检索值:

const model = form.value // --> Expected to be IUser

以强类型方式,如果相应的 FormControl 缺少/类型不正确,则删除字段或添加新字段会导致编译问题,并且编译器可以保证表单值符合接口吗?

所以

form.value as IUser
还不够好,也不能忽略 `

的类型
angular angular-forms
1个回答
0
投票

好吧,这样的事情似乎可行,但我想知道是否有更可靠的方法来做到这一点?我猜这会开始出现嵌套字段和数组的各种问题:

type Controls<T> = {
  [P in keyof T]: FormControl<T[P]>
}

form = new FormGroup<IUser>({
  name: new FormControl<string>(..)
  age: new FormControl<number>(...)
});

const model = form.value as Partial<IUser>;  // Any way to enforce this is not a partial?

© www.soinside.com 2019 - 2024. All rights reserved.