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
The FormGroup API exposes methods such as addControl and removeControl which you can use to add or remove controls from your form group after it has been initialized.
An example using these methods might look like:
formMode: 'add' | 'update';
userForm: FormGroup;
ngOnInit() {
this.form = this.formBuilder.group({
firstName: [''],
lastName: ['']
});
}
changeMode(mode: 'add' | 'update') {
if (mode === 'add') {
if (!this.form.get('firstName')) {
this.form.addControl('firstName');
}
this.form.removeControl('lastName');
} else {
if (!this.form.get('lastName')) {
this.form.addControl('lastName');
}
this.form.removeControl('firstName');
}
}
onChange(event: 'add' | 'update') {
this.changeMode(event);
}
You'll probably want your DOM to reflect the state of your form by adding *ngIf checks based on the existence of a given control: