0

I am new to Angular. I want to create a dynamic Form for Survey. Survey Questions and input types are fully dynamic and may change as per the Area. We are taking this in the form of JSON from API call.

Below is the code snippet.

.ts File

export class MaintenanceSurveyComponent implements OnInit {
  myFormTemplate: any = []; 
  myFormGroup: FormGroup = new FormGroup({});
  
  WOId;
  @Input() public user;
  constructor(private maintenanceService: MaintenanceRequestService) { }

  ngOnInit() {
   this. myFormGroup = new FormGroup({});
    this.maintenanceService.getSurveyquestions(this.user)
      .subscribe((res: any) => {
        this.myFormTemplate = JSON.parse(res);        
    });
    let group = {}
    this.myFormTemplate.forEach(input_template => {
      group[input_template.hMy] = new FormControl({ value: input_template.hMy});
    })
    this.myFormGroup = new FormGroup(group);    
  }

  onSubmit() {
    alert('SUCCESS!! :-)\n\n' + JSON.stringify(this.myFormGroup.getRawValue(), null, 4));
    console.log(this.myFormGroup.getRawValue());
    console.log("this is test");
  }

}

.html File

<form [formGroup]="myFormGroup" (ngSubmit)="onSubmit()">
    <div class="modal-header border-0">
      <h5 class="modal-title" id="addMaintenanceRequestsTitle">Maintenance Survey</h5>
      <button type="button" class="close" data-dismiss="modal" aria-label="Close">
        <span aria-hidden="true">&times;</span>
      </button>
    </div>
    <div class="modal-body">
      <div class="row">
        <div class="col-lg-7">

          <div *ngFor="let form_elem of myFormTemplate">
            <div [ngSwitch]="form_elem.type">
              <div class="form-row">
                <div class="form-group col-md-12 mb-2" *ngSwitchCase="'textbox'">
                  <label class="text-sm font-weight-bold mb-1">{{form_elem.label}} </label>
                  <!--  <input type="text" formControlName="{{form_elem.hMy}}" />-->                
                  <input type="text"  formControlName="{{form_elem.hMy}}" required="{{form_elem.IsRequired}}" ngDefaultControl />
                </div>
              </div>
              <div class="form-row">
                <div class="form-group col-md-12 mb-2" *ngSwitchCase="'number'">
                  <label class="text-sm font-weight-bold mb-1">{{form_elem.label}} </label>
                  <!--<input type="number" formControlName="{{form_elem.label}}" />-->                  
                  <input type="number" formControlName="{{form_elem.hMy}}" required="{{form_elem.IsRequired}}" ngDefaultControl />
                </div>
              </div>
              <div class="form-row">
                <div class="form-group col-md-12 mb-2" *ngSwitchCase="'select'">
                  <!--<select formControlName="{{form_elem.label}}">-->               
                  <label class="text-sm font-weight-bold mb-1">{{form_elem.label}} </label>
                  <select  formControlName="{{form_elem.hMy}}" required="{{form_elem.IsRequired}}" ngDefaultControl >
                    <option *ngFor="let opt of form_elem.options">
                      {{opt}}
                    </option>
                  </select>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
    <div class="modal-footer justify-content-start">
      <button type="submit" value="save" class="btn btn-primary">Submit</button>
    </div>
    <!--<input type="submit" value="save" />-->
  </form>

Error:

ERROR Error: Cannot find control with name: 'textbox88'
    at _throwError (forms.js:2293)
    at setUpControl (forms.js:2201)
    at FormGroupDirective.push../node_modules/@angular/forms/fesm5/forms.js.FormGroupDirective.addControl (forms.js:5427)
    at FormControlName.push../node_modules/@angular/forms/fesm5/forms.js.FormControlName._setUpControl (forms.js:6028)
    at FormControlName.push../node_modules/@angular/forms/fesm5/forms.js.FormControlName.ngOnChanges (forms.js:5949)
    at checkAndUpdateDirectiveInline (core.js:21092)
    at checkAndUpdateNodeInline (core.js:29494)
    at checkAndUpdateNode (core.js:29456)
    at debugCheckAndUpdateNode (core.js:30090)
    at debugCheckDirectivesFn (core.js:30050)

I tried various solutions but no luck. I am using Angular 8. I appreciate your help on this.

1
  • Since subscribe call is asynchronus move dynamic formcreation inside subscribe method and check Commented Oct 28, 2020 at 16:31

1 Answer 1

1

You need to move the form creation inside the subscribe method and wait for the response because it is an asynchronous call.

export class MaintenanceSurveyComponent implements OnInit {
    myFormTemplate: any = [];
    myFormGroup: FormGroup = new FormGroup({});

    @Input() public user;
    constructor(private maintenanceService: MaintenanceRequestService) {}

    ngOnInit() {
        this.myFormGroup = new FormGroup({});
        this.maintenanceService.getSurveyquestions(this.user).subscribe((res: any) => {
            this.myFormTemplate = JSON.parse(res);

            let group = {};
            this.myFormTemplate.forEach((input_template) => {
                group[input_template.hMy] = new FormControl({ value: input_template.hMy });
            });
            this.myFormGroup = new FormGroup(group);
        });
    }

    onSubmit() {
        alert('SUCCESS!! :-)\n\n' + JSON.stringify(this.myFormGroup.getRawValue(), null, 4));
        console.log(this.myFormGroup.getRawValue());
        console.log('this is test');
    }
}
Sign up to request clarification or add additional context in comments.

1 Comment

Perfect. Thanks for help, you are great man. I dint realize that and wasted many hours to solve this.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.