while building crud app in angular 5 I\'ve come across with a question, how can I use the same form builder but change what form controls I get depending on what I want, adding
First you can create group of template basis of your option. We can use *ngIf in template to hide and show group of elements in form. Then use formBuilder to create form instance of form each time pass only object of those form controls which are enable.
Template
Angular class
export class AppComponent implements AfterViewInit {
public myForm: FormGroup;
lNameEmail1 = false;
lNameEmail2 = false;
myFormProperty1 = {
"fname": new FormControl("", Validators.required)
};
myFormProperty2 = {
"fname": new FormControl("", Validators.required),
"lname": new FormControl("", Validators.required),
"email": new FormControl("")
};
myFormProperty3 = {
"fname": new FormControl("", Validators.required),
"lname2": new FormControl("", Validators.required),
"email2": new FormControl("")
};
constructor(public fb: FormBuilder) {
this.myForm = this.fb.group(this.myFormProperty1);
}
formGrp1(){
alert('Form 1 enable')
this.lNameEmail1 = true;
this.lNameEmail2 = false;
this.myForm = this.fb.group(this.myFormProperty2);
this.myForm.valueChanges.subscribe(data =>
console.log('form object ====' + JSON.stringify(data)
));
}
formGrp2(){
alert('Form 2 enable')
this.lNameEmail1 = false;
this.lNameEmail2 = true;
this.myForm = this.fb.group(this.myFormProperty3);
this.myForm.valueChanges.subscribe(data =>
console.log('form object ====' + JSON.stringify(data)
));
}
onSubmit() {
console.log('Form submitted Value=='+ JSON.stringify(this.myForm.value));
}
}