表单控件更新值在ngOnInit()中不更新

时间:2018-05-22 10:42:03

标签: angular

我在ngOnInit()

中从JSON创建动态表单

我想要做的是在ngOnInit()的末尾手动设置一些表单控件。

ngOnInit(){
  ...Form creation...
  this.parsedJson.sections[0].form.controls['clientName'].setValue("John");
}

它不会以这种方式更新控件,如果我手动触发相同的操作(例如:按钮点击),它将进行更新。
this.parsedJson.sections[0].form.controls['clientName'].setValue("John");

我也尝试使用patchValue代替setValue,但结果是一样的。

表单创建:

for(let section of this.parsedJson2.sections){
  section.form  = new FormGroup({});
  if(section.section_type == 'normal') {
    for (let question of section.question_list) {
      if (question.qtype == 'input-text') {
        const control: FormControl = new FormControl(question.answer, Validators.required);
        section.form.addControl(question.key, control);
      }
      if (question.qtype == 'input-email') {
        const control: FormControl = new FormControl(question.answer, Validators.email);
        section.form.addControl(question.key, control);
      }
      if (question.qtype == 'multi-choice') {
        for (let choice of question.qchoices) {
          const control: FormControl = new FormControl(choice.selected, Validators.required);
          section.form.addControl(choice.key, control);
        }
      }
      else {
        const control: FormControl = new FormControl(question.answer, Validators.required);
        section.form.addControl(question.key, control);
      }
    }
  }
}

1 个答案:

答案 0 :(得分:1)

您必须更新 ngAfterViewInit 中的控件。

这是因为在完全初始化视图之前会调用 ngOnInit

此处有更多信息:Angular Lifecycle Hooks