0

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

数据来自 api 调用成功。我相信我的问题是 [questions] 在数据准备好之前具有约束力。有人可以告诉我更好的方法吗,或者请对我做错的事情提供任何建议?有没有办法可以先在 api 中设置属性?

下面我的方法看起来像:

文件

 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) 处未定义的属性“有效”

4

1 回答 1

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);
 }
于 2018-09-20T08:27:53.997 回答