我的Angular总结:建议使用FormGroup.controls 来访问子表单控件

在 Angular 中,我们至少有两种方法可以访问子表单控件:FormGroup.get('controlPath')FormGroup.controls.controlPath。到目前为止,为了类型安全,我选择使用后者。

考虑到下面的代码:

ts 复制代码
@Component({
  selector: 'app-root',
  templateUrl: './app/playground.component.html',
  imports: [FormsModule, ReactiveFormsModule],
})
export class PlaygroundComponent {
  formGroup = this.formBuilder.group({
    booker: new FormControl('123', {validators: [Validators.required]}),
    bookNames: this.formBuilder.array<string>([]),
    bookerConf: this.formBuilder.group({language: ''})
  });
  constructor(private formBuilder: FormBuilder) {
    const bookerFromControl = this.formGroup.controls.booker; // FormControl<string | null>
    const bookerFromGetPath = this.formGroup.get('booker'); // AbstractControl<string | null, string | null> | null
    const bookerFromGetPaths = this.formGroup.get(['booker']); // AbstractControl<any, any> | null
    const bookerFromGetPathsWithConst = this.formGroup.get(['booker'] as const); // AbstractControl<string | null, string | null> | null
    
    const bookNameFromControls = this.formGroup.controls.bookNames; // FormArray<FormControl<string | null>>
    const bookNamesFromPath = this.formGroup.get('bookNames'); // AbstractControl<(string | null)[], (string | null)[]> | null
    const bookNamesFromPaths = this.formGroup.get(['bookNames']); // AbstractControl<any, any> | null
    const bookNamesFromPathsWithConst = this.formGroup.get(['bookNames'] as const); // AbstractControl<(string | null)[], (string | null)[]> | null
  }
}

如你所见,formGroup.get 至少有两个问题

  • 无法识别是否存在 booker 字段,因此 bookerFromGetPath 的类型可能是 null

    • 当键入错误的表单控件名称时,例如 formGroup.get('booker1'),不会有任何错误提示。
    • 同样,当你想要利用 VSCode 的重构功能对 booker 字段名称进行批量修改时,formGroup.get('booker') 并不会被自动改掉。
    • 使用路径数组参数时类型变得更糟,如 formGroup.get(['booker'])。但对于这种情况,我们可以使用as const,例如formGroup.get(['booker'] as const)来改善这种情况。
  • bookerFromGetPath 返回了错误的类型,AbstractControl 而不是 FormControl

    • 这不是一个大问题,因为 AbstractControl 类似于 FormControl
    • 但是对于 bookNameFromControlsFormArrayAbstractControl 之间的差异很大。

有一个开放的问题 严格类型的 FormGroup 应该有严格类型的 "get" 访问器 在2024年11月16日提出。

截至2025年4月20日,这个问题仍未解决,而且该问题只关注了我们发现的第一个问题。

不管怎样,这就是我选择的原因。

相关推荐
像风一样自由20202 小时前
HTML与JavaScript:构建动态交互式Web页面的基石
前端·javascript·html
aiprtem2 小时前
基于Flutter的web登录设计
前端·flutter
浪裡遊2 小时前
React Hooks全面解析:从基础到高级的实用指南
开发语言·前端·javascript·react.js·node.js·ecmascript·php
why技术3 小时前
Stack Overflow,轰然倒下!
前端·人工智能·后端
GISer_Jing3 小时前
0704-0706上海,又聚上了
前端·新浪微博
止观止3 小时前
深入探索 pnpm:高效磁盘利用与灵活的包管理解决方案
前端·pnpm·前端工程化·包管理器
whale fall3 小时前
npm install安装的node_modules是什么
前端·npm·node.js
烛阴3 小时前
简单入门Python装饰器
前端·python
袁煦丞4 小时前
数据库设计神器DrawDB:cpolar内网穿透实验室第595个成功挑战
前端·程序员·远程工作
天天扭码4 小时前
从图片到语音:我是如何用两大模型API打造沉浸式英语学习工具的
前端·人工智能·github