1

I am creating dynamic form by getting data from backend. how can i use formcontrol. i getting error stating Cannot find control with name: 'obj.name'. how can i initializeForm by iterating over toolData instead hard code intializing.

initializeForm(){
   // here i am intializing manually how can i initialize by iterating over toolData 
    this.formValue=this.fb.group({
      uname:['',[Validators.required,Validators.pattern('^[a-zA-Z \-\']+')]],
      xyz:['',[Validators.required]],
      abc:['',[Validators.required]],
    })
  }
<form [formGroup]="formValue">
    <span *ngFor="let obj of toolData">
       <label for="obj.name">{{obj.label}}</label>
       <input type="obj.type" id="obj.name" name="obj.name" formControlName="obj.name" value="obj.value" required="obj.required" />
    </span>
</form>
toolData=[{"type":"text","name":"uname","label":"user Name","value":"default","required":true},
    {"type":"number","name":"xyz","label":"Sample Value","value":"1","min":0,"max":100,"required":true},
    {"type":"number","name":"abc","label":"ABC ","value":"6","min":0,"max":100,"required":true}]

2 Answers 2

1
constructor(
    ...
    private formBuilder: FormBuilder,
    ...
) {}

  ngOnInit(): void {
  this.initForm(); // init form with default values before u get response from server
    // after getting data from server call initControls()
  }

  // convenience getters for easy access to form fields
  get controls(): {[key: string]: AbstractControl} { return this.form.controls; }
  get someControls(): FormArray { return this.controls.someControls as FormArray; }

initForm(): void {
    this.form = this.formBuilder.group({
      someControls: new FormArray([])
    });
}

initControls(): void {
const someControlFormGroup = this.formBuilder.group({
      name: [defaultValue, [Validators.required]],
    });
    this.someControls.push(someControlFormGroup);
}

now you can just use formControlName while each controls in template

Sign up to request clarification or add additional context in comments.

Comments

0

property binding has been done incorrectly, trying the below code.

[formControlName]="obj.name"

for more detail, please see the https://angular.io/guide/property-binding

Comments

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.