我是 Angular 的新手。我遇到了具有三种变体的代码。我想知道这三者在响应式表单(表单组、表单构建器和表单控件)中的实现有什么区别。
是否有任何基于应用程序性能的优先级高于另一种方式,还是只是偏好?
addressFormControl = new FormControl(undefined, [
Validators.required,
Validators.address,
]);
export class BusinessComponent {
BusinessForm = new FormGroup({
email: this.emailFormControl,
firstName: new FormControl(''),
lastName: new FormControl(''),
address: new FormGroup({
street: new FormControl(''),
city: new FormControl(''),
state: new FormControl(''),
zip: new FormControl('')
})
});
}
export class BusinessComponent {
constructor(private fb: FormBuilder) { }
businessForm = this.fb.group({
business: this.businessFormControl,
firstName: [''],
lastName: [''],
address: this.fb.group({
street: [''],
city: [''],
state: [''],
zip: ['']
}),
});
}
最佳答案
举个例子。当存在以下用例时,您可以使用它
formControl: 当您的 UI 设计中只有很少(可能是一个或两个)独立字段时,可能是一个输入。所以不需要表单标签。
formGroup: 当您的表单包含多个输入、下拉菜单和单选按钮时。所有这些你都想创建一个 JSON 对象来传入 API。
formBuilder: 当您拥有动态表单时。例如,有地址栏输入。用户可以通过单击“添加新行”按钮来添加尽可能多的输入栏。那时您可以利用创建动态 formControls。
所有这些都为您提供了在语义上一起创建一个组的选项,否则,所有这些也可以仅使用 formControl 来实现。
希望您能与这些用例相关
关于响应式表单中的 Angular 表单组与表单控件和表单生成器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/69604976/