如何在Angular 2中验证动态表单

时间:2016-02-19 10:43:11

标签: angular angular2-forms

我根据来自API的数据动态生成表单。我成功地完成了表单的实现,尽管每当我尝试调用'form.valid'方法时我仍然会收到错误。

以下是我的代码片段:

模板文件

ExtAudioRecorder: prepare() method called on illegal state
ExtAudioRecorder: start() called on illegal state

组件类

<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>

如您所见,表单从外部源加载问题,用户可以添加新问题或删除其他一些问题。 输入控件标识符是动态生成的我将它保存在模板'questionInput'中的局部变量中然后我使用它将控件添加到我的控件组'addControlName'我定义ngControl。

之前的代码是一个片段,完整的代码完全正常工作每当我收到错误响应或错过任何问题时我都会看到错误。每当我使用'questionsForm.valid'而不是模板或组件时,问题就出现了,它给了我这个错误:

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.
   }
}

我做错了什么,我是Angular的新手,提前谢谢。

0 个答案:

没有答案