Multiple Dynamic Submit Button Form In Angular
I have to make a single submit. But i will show the user 4 forms dynamically fields: any = [ [ { label: 'firstname', name: 'first' }, { label: '
Solution 1:
In order to build your form dynamically you should define FormGroup and build your form using formBuilder based on what you want, for example: Component.ts
import { FormGroup, FormBuilder, Validators, FormControl} from '@angular/forms';
constructor(private formBuilder: FormBuilder) { }
ngOnInit() {
//Call the Create functionthis.createDynamicForm(this.formIndex);
}
public myFormGroup : FormGroup;
formIndex = 0; // The index of fields array, Form you want to build
fields: any = [
[
{ label: "firstname", name: "first" },
{ label: "lastname", name: "last" },
{ label: "Date", name: "fromDate", type: "date" },
{ label: "To Date", name: "toDate", type: "date" },
],
[
{ label: "firstname", name: "first" },
{ label: "lastname", name: "last" },
{ label: "age", name: "age"},
{ label: "address", name: "add" },
],
[
{ label: "firstname", name: "first" },
{ label: "lastname", name: "last" },
{ label: "mobile", name: "mob" },
],
]
private createDynamicForm(formIndex) { //create form based on fields arraythis.myFormGroup = this.formBuilder.group(this.createFormGroup(formIndex));
}
private createFormGroup(formIndex){ // define each field name and validator - defualt value ...etcvar _group = {}
for (var i = 0; i < this.fields[formIndex].length; ++i) {
_group[this.fields[formIndex][i].name] = ['',Validators.required]
}
return _group;
}
submitDynamicForm(formIndex){ // I'm Just log the input @todofor (var i = 0; i < this.fields[formIndex].length; ++i) {
console.log(this.fields[formIndex][i].name,this.myFormGroup.get([this.fields[formIndex][i].name]).value)
}
}
and your template should be like this
<form [formGroup]="myFormGroup" (ngSubmit)="submitDynamicForm(formIndex)"><div *ngFor="let inputField of fields[formIndex]"><inputtype="text"id="{{inputField.name}}_id" [formControlName]="inputField.name"><labelfor="{{inputField.name}}_id">{{inputField.label}}</label></div><inputtype="submit" [disabled]="!myFormGroup.valid"type="submit"value="submit"></form>
Post a Comment for "Multiple Dynamic Submit Button Form In Angular"