角度为6的动态表单创建

时间:2018-09-19 13:36:47

标签: angular6 angular-forms angular-formbuilder

我试图开始在Angular 2中创建动态表单,并且正在使用Angular文档中的设置。我的设置没有任何问题,只是将服务中的数据硬编码为api调用。我的问题是,当我尝试使用api调用时,动态表单创建失败。

数据已成功从api调用中传入。我相信我的问题是[questions]在数据准备就绪之前就已绑定。有人可以告诉我一种更好的方法吗,或者请提供任何建议以解决我做错的事情?有没有一种方法可以首先在api中设置属性?

在下面,我的方法看起来像:

TS文件

 export class DynamicFormComponent implements OnInit {

 @Input() questions: QuestionBase<any>[] = [];
 form: FormGroup;
 payLoad = '';

 constructor(private qcs: QuestionControlService ,private dy :QuestionService) {  }

 ngOnInit() {
this.questions=this.dy.getDataFromService();
this.form = this.qcs.toFormGroup(this.questions);
 }

onSubmit() {
 this.payLoad = JSON.stringify(this.form.value);
 }
 }

HTML

    <div>
      <form (ngSubmit)="onSubmit()" [formGroup]="form" *ngIf="isFormReady">

        <div *ngFor="let question of questions" class="form-row">
         <app-question [question]="question" [form]="form"></app-question>
        </div>
        <div class="form-row">
         <button type="submit" [disabled]="!form.valid">Save</button>
        </div>
      </form>
     <div *ngIf="payLoad" class="form-row">
       <strong>Saved the following values</strong><br>{{payLoad}}
     </div>
   </div>
##QUESTIONSERVICE.TS

getDataFromService(){
let questions: QuestionBase<any>[]=[];
this.auth.dynamicFormData().subscribe(
    (result) => {
        let data=result;
        for(var i=0;i<data.length;i++){
            questions.push(new TextboxQuestion(data[i]));
        }

    }); 
return questions.sort((a, b) => a.order - b.order);
}
}

API的结果数据是

[{"value":"Sireesha_0","key":"firstName_0","label":"First Name_0","required":true,"order":1,"controlType":"text"},{"value":"Sireesha_1","key":"firstName_1","label":"First Name_1","required":true,"order":1,"controlType":"text"}]

错误

发生错误:无法读取未定义的属性“有效”

在错误拦截器TypeError中遇到的错误:无法读取DynamicFormQuestionComponent.get [as isValid]中未定义的属性“有效”(dynamic-form-question.component.ts:13)

1 个答案:

答案 0 :(得分:0)

我已经像下面那样更改了代码,并且运行良好。

html

  <form (ngSubmit)="onSubmit()" [formGroup]="form" *ngIf="isFormReady">

    <div *ngFor="let question of questions" class="form-row">
     <app-question [question]="question" [form]="form"></app-question>
    </div>
    <div class="form-row">
     <button type="submit" [disabled]="!form.valid">Save</button>
    </div>
  </form>

ts

 isFormReady:booelan;

ngOnInit() {
  this.questions=this.dy.getDataFromService();
}


getDataFromService(){
  let questions: QuestionBase<any>[]=[];
  this.auth.dynamicFormData().subscribe(
  (result) => {
    let data=result;
    for(var i=0;i<data.length;i++){
        questions.push(new TextboxQuestion(data[i]));
    }

 }); 
  this.form = this.qcs.toFormGroup(this.questions);
  this.isFormReady=true;
return questions.sort((a, b) => a.order - b.order);
 }