【发布时间】:2019-08-07 18:53:48
【问题描述】:
我遇到的问题是当我尝试将列表数据放入选择下拉列表时
我从这里尝试了一个解决方案formGroup expects a FormGroup instance 但没有运气
我的组件如下所示:
export class LandingPageComponent {
submitted = false;
oppoSuits: any = ['Men', 'Women', 'Boys', 'Inspiration']
constructor(public fb: FormBuilder) { }
oppoSuitsForm = this.fb.group({
name: ['', [Validators.required]]
})
changeSuit(e) {
this.oppoSuitsForm.get('name').setValue(e.target.value, {
onlySelf: true
})
}
public handleError = (controlName: string, errorName: string) => {
return this.oppoSuitsForm.controls[controlName].hasError(errorName);
}
ngOnInit() {
this.oppoSuitsForm = new FormGroup({
name: new FormControl(""),
});
};
onSubmit() {
this.submitted = true;
alert(JSON.stringify(this.oppoSuitsForm.value))
}
}
和html文件:
<form [formGroup]="oppoSuitsForm" (ngSubmit)="onSubmit()">
<select formControlName="name" (change)="changeSuit($event)">
<option value="">Choose oppo suit</option>
<option *ngFor="let suit of oppoSuits">{{suit}}</option>
</select>
<div class="error-block" *ngIf="submitted && handleError('name', 'required')">
You must provide a value!
</div>
<button>Submit</button>
</form>
在控制台我得到这个: 错误:formGroup 需要一个 FormGroup 实例
和:
无法读取未定义的属性“get”
【问题讨论】:
-
试试
<form [formGroup]="oppoSuitsForm" (ngSubmit)="onSubmit()" *ngIf="oppoSuitsForm">表单实际上是异步的 -
如果我尝试使用 *ngIf="" 表单正在消失
-
是的,没看代码。我现在看到您还有其他问题。
标签: angular