我正在尝试通过两种方式创建表单。第一种方法可行,但第二种方法会出错。这是我所做的:
//the first approach
this.form = this.formBuilder.group({
location: ['', Validators.required],
weather: this.formBuilder.group({
rainy: ['', Validators.required],
sunny: ['', Validators.required]
}),
});
//the second approach
this.form.addControl('location', new FormControl('', [Validators.required]), { emitEvent: false });
this.form.addControl('weather', new FormGroup([]), { emitEvent: false });
(<FormGroup>this.form.controls['weather']).addControl('rainy',
this.formBuilder.control('', [Validators.required]), { emitEvent: false }
);
(<FormGroup>this.form.controls['weather']).addControl('sunny',
this.formBuilder.control('', [Validators.required]), { emitEvent: false }
);
当我使用第二种方法时,出现两个错误:
TypeError: this.form is undefined
formGroup expects a FormGroup instance. Please pass one in.
然后我发现,如果我将
*ngIf="form"
添加到我的表单标签中,第二个错误就会消失,但第一个错误不会消失。
有人知道第二种方法有什么问题吗?
P.s.我不知道调用这两种方法的最佳方式是什么!它们有没有特定的名称,例如静态表单声明或动态表单声明或其他名称?