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}]
CodePudding user response:
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 controls(): 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
CodePudding user response:
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