我的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日,这个问题仍未解决,而且该问题只关注了我们发现的第一个问题。

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

相关推荐
不懂的浪漫几秒前
AI 时代还需要买课吗?我用 Skills + Markdown + HTML 搭了一套自学系统
前端·人工智能·html·skill
前端的阶梯3 分钟前
Conda 开发 Python 程序完全指南
前端·人工智能·后端
zhengfei6116 分钟前
第2章 Agent 核心组件深度解析
前端·javascript·react.js
Linsk11 分钟前
前端代码压缩对浏览器兼容性的影响
前端
yingyima15 分钟前
凌晨3点的闹钟:分布式定时任务设计实战
前端
用户814238611884116 分钟前
iOS ObjectC棕地应用集成Expo(React Native)的过程及踩坑
前端
lichenyang45320 分钟前
HMRouter 完整能力清单:从初始化到拦截器/对话框/生命周期/转场动画一站式查阅
前端
lichenyang45331 分钟前
鸿蒙电商 Demo v2:真实商品接口 + 支付/订单闭环 + 收藏功能,外加一个 ArkUI V2 @Builder 响应式断链的硬核坑
前端·后端
前端的阶梯31 分钟前
如何节省你的token,请看CodeGraph
前端·人工智能·后端
万少1 小时前
产品原型不用从零画 -GPT 出图,Gemini 生成 HTML
前端·javascript·后端