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' のローカル変数に保持し、これを使用してコントロール グループ 'addControlName' にコントロールを追加し、ngControl を定義します。
前のコードはスニペットです。完全なコードは完全に機能しています。エラー応答を受け取ったり、質問を見逃したりするたびにエラーが表示されます。テンプレートまたはコンポーネント自体ではなく、「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 は初めてです、よろしくお願いします。