我有一个根据来自 API 的数据动态生成的表单。尽管每当我尝试调用“form.valid”方法时仍然出现错误,但我成功地完全实现了表单。
这是我的代码片段:
模板文件
<form (ngSubmit)="update()" [ngFormModel]="questionsForm">
<div *ngFor="#question of questions; #i=index" >
<input type="hidden" #questionInput [value]="'qu['+(question.id)+']'" class="hidden"/>
{{addControlName(questionInput.value)}}
<div class="col-xs-11">
<input type="text" ngControl="{{questionInput.value}}" name="{{questionInput.value}}[title]"
[(ngModel)]="question.title" >
<label >Title</label>
<control-message [control]="questionInput.value" ></control-message>
</div>
<!-- Some More fields -->
<!-- Some More fields -->
<!-- Some More fields -->
</div>
<button type="submit"> Submit</button>
<!--<button type="submit" [disabled]="!questionsForm.valid"> Submit</button>-->
</form>
组件类
export class QuestionsComponent {
private questionsForm;
private questions:Array<Question>;
private errors:any = {};
constructor(private _fb:FormBuilder) {
}
ngOnInit() {
this.questionsForm = new ControlGroup({});
}
addControlName(name) {
if (!this.questionsForm.contains(name)) {
var control = new Control("", Validators.compose([Validators.required]));
this.questionsForm.addControl(name, control);
}
}
removeQuestion(questionId:string) {
this.questions = this.questions.filter((question:Question) => {
if (question.id != questionId) {
return true;
}
return false;
});
}
newQuestion() {
// this.questions.push(newQuestion); here I append question whenever the user clicks on 'add new question' button.
}
private _setErrors(errors:any):void {
this.questionsForm.response = errors;
ValidatorService.setErrors(errors.errors, this.questionsForm);
}
private getQuestions():void {
// this.questions = Question.castArray(data.data); here I load questions from external source.
}
}
如您所见,表单从外部源加载问题,用户可以添加新问题或删除其他一些问题。输入控件标识符是动态生成的,我将其保存在模板“questionInput”中的局部变量中,然后我使用它将控件添加到我定义的 ngControl 控件组“addControlName”中。
之前的代码是一个片段,完整的代码完全可以工作,每当我收到错误响应或错过任何问题时,我都会看到错误。每当我使用“questionsForm.valid”而不是在模板或组件中使用它自己时,问题就会出现,它给了我这个错误:
EXCEPTION: Expression '!questionsForm.valid in QuestionsComponent@308:36' has changed after it was checked. Previous value: 'false'. Current value: 'true' in [!questionsForm.valid in QuestionsComponent@308:36]
ORIGINAL EXCEPTION: Expression '!questionsForm.valid in QuestionsComponent@308:36' has changed after it was checked. Previous value: 'false'. Current value: 'true'
我做错了什么吗,我是Angular的新手,在此先感谢。