我遇到的问题是当我尝试将列表数据放入选择下拉列表中时
我从这里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”
答案 0 :(得分:0)
您两次定义表单组。您只需要实例化一次,我建议在构造函数中进行实例化。
@Component({...})
export class Component {
oppoSuitsForm: FormGroup;
constructor (private fb: FormBuilder) {
this.oppoSuitsForm = this.fb.group({
name: ['', [Validators.required]]
});
}
}
这应该可以解决您的两个错误。