我的表单
public loginForm = new FormGroup({
username: new FormControl('', [Validators.required]),
password: new FormControl('', [Validators.required, Validators.minLength(8)]),
});
当获取表单的值时,这是其类型
getRawValue(): {
username: string | null;
password: string | null;
}
我知道我可以这样做来抑制null的
public loginForm = new FormGroup({
username: new FormControl('', { nonNullable: true, validators: [Validators.required] }),
password: new FormControl('', { nonNullable: true, validators: [Validators.required, Validators.minLength(8)] }),
});
但是有没有一种方法可以使所有表单控件在默认情况下不可调用
如果我的表单包含大量控件,我将不得不在所有上使用nonNullable: true
您可以使用NonNullableFormBuilder,这样可以删除与设置nonNullable相关的样板
const fb = new FormBuilder();
const loginForm = fb.nonNullable.group({
username: ['', [Validators.required]],
password: ['', [Validators.required, Validators.minLength(8)]],
});
注射器的另一个例子:
@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)]],
});
}
}