I am working on a simple webpage that includes a form group with multiple controls. In my ngOnInit method, I am sending a get request to fetch data from the server. While waiting for this data to load, I want to hide the form and only display it once the data is retrieved.
Below is a snippet from my .component.ts
file:
public formGroup = new FormGroup({
firstName: new FormControl('', [
Validators.required,
]),
lastName: new FormControl('', [
Validators.required,
]),
});
Here is my ngOnInit()
method:
ngOnInit() {
this.route.params.pipe(mergeMap(params => {
this.param1 = params['param'];
this.hideForm(); //Implementation of this method is needed
return this.service.getInfo(this.param1);
})).subscribe(data => {
// Successful case - data loaded, form should be shown
this.formGroup.controls['firstName'].setValue(data.firstName);
this.formGroup.controls['lastName'].setValue(data.lastName);
}, err => {
// Error case - form should remain hidden
});
}
Snippet from my component.html
file:
<form [formGroup]="formGroup" (ngSubmit)="handleSubmit()">
<mat-form-field>
<input matInput placeholder="Name" formControlName="firstName" required>
</mat-form-field>
<mat-form-field>
<input matInput placeholder="Surname" formControlName="lastName" required>
</mat-form-field>
</form>
I have come across suggestions to dynamically add/remove controls from the form, but I feel like this is unnecessary for me as I prefer hiding/showing components instead. Any thoughts or ideas on this would be highly appreciated.