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 or updating users thru form...
Here's some simple code, I will try not to complicate things, since I have pretty big form with lot of attributes...
So in my app.component.html i have form
<form class="form-horizontal" [formGroup]="form" #myForm="ngForm"
(ngSubmit)="save()">
<div class="form-group">
<label for="firstName" class="control-label
required">First name</label>
<input type="text" id="firstName" class="form-control"
formControlName="firstName">
</div>
<div class="form-group">
<label for="lastName" class="control-label
required">Last name</label>
<input type="text" id="lastName" class="form-control"
formControlName="lastName">
</div>
and in my app.component.ts
in my constructor i have
this.form = this.formBuilder.group({
firstName: ['', [Validators.required, Validators.minLength(2),
Validators.pattern(/^[a-zA-Z]+$/)]],
lastName: ['', [Validators.required, Validators.minLength(2),
Validators.pattern(/^[a-zA-Z]+$/)]],
});
and save() function for submiting the form
save() {
let formModel = this.form.value;
formModel.id = this.Id;
if (this.Id == null) {
this._usermanagementservice.addEmployee(formModel).subscribe(() => {
//function that reloads table with employees
this.LoadAllEmployees();
});
}
else {
this._usermanagementservice.updateEmployee(this.Id, formModel).subscribe(() => {
this.LoadAllEmployees();
});
}
}
Noted that everything works, I've not included other fields, but here's the question, how can I include only form for first name field on adding user, and have ONLY last name for updating? (to simplfy things, I'm using this example first and last name)
Thanks, If you need more info, I'll gladly provide it Ps. english is my secondary language, so terms like fields, forms and etc. are for sure incorrect, hopefully you'll get the point
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:
<input *ngIf="form.get('lastName')" formControlName="lastName">