有没有办法让表单值默认为不可空?

the*_*yer 10 typescript angular

我的表格

  public loginForm = new FormGroup({
    username: new FormControl('', [Validators.required]),
    password: new FormControl('', [Validators.required, Validators.minLength(8)]),
  });
Run Code Online (Sandbox Code Playgroud)

当获取表单的值时,这是它的类型

getRawValue(): {
  username: string | null;
  password: string | null;
}
Run Code Online (Sandbox Code Playgroud)

我知道我可以这样做来抑制空值

  public loginForm = new FormGroup({
    username: new FormControl('', { nonNullable: true, validators: [Validators.required] }),
    password: new FormControl('', { nonNullable: true, validators: [Validators.required, Validators.minLength(8)] }),
  });
Run Code Online (Sandbox Code Playgroud)

但是有没有办法让所有表单控件默认都不可为空呢?

如果我的表单包含很多控件,我将不得不使用 nonNullable: true所有控件

Rac*_*naa 14

您可以使用NonNullableFormBuilder,这样您就可以删除与设置 nonNullable 相关的样板

  const fb = new FormBuilder();
  const loginForm = fb.nonNullable.group({
    username: ['', [Validators.required]],
    password: ['', [Validators.required, Validators.minLength(8)]],
  });
Run Code Online (Sandbox Code Playgroud)

另一个使用注射器的例子:

@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: [ './app.component.css' ]
})
export class AppComponent  {
  name = 'Angular ' + VERSION.major;
  loginForm: FormGroup
  
  constructor(private readonly fb: NonNullableFormBuilder) {
    this.loginForm = fb.group({
      username: ['', [Validators.required]],
      password: ['', [Validators.required, Validators.minLength(8)]],
    });
  }

}
Run Code Online (Sandbox Code Playgroud)