在使用FormGroup.get()获取表单控件值时,需要考虑到其可能为空的情况,因此可以采用可选链操作符(?.)来处理。示例代码如下:
import { Component } from '@angular/core';
import { FormGroup, FormControl } from '@angular/forms';
@Component({
  selector: 'my-app',
  template: `
    
    
  `,
})
export class AppComponent {
  form = new FormGroup({
    name: new FormControl(null),
  });
  onSubmit() {
    // 使用可选链操作符(?.)来解决可能为空的问题
    const name = this.form.get('name')?.value;
    
    console.log('Name:', name);
  }
}
在以上示例中,我们使用了可选链操作符(?.)来获取表单控件值,这样即使FormGroup.get()返回了null,也不会报错,而是直接返回undefined。这样就可以避免出现类型不匹配、空指针等问题。
                    上一篇:Angular14到15的更新导致库中构造函数参数的兼容性错误
                
下一篇:Angular14的渐进式网络应用(PWA)无法在横屏模式下运行,即使配置好了清单文件,并且使用最新版本的Android。