What is a way to conceal an Angular Material FormGroup on the webpage until the data has been retrieved from the background?

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.

Answer №1

Retrieve the incoming data and store it in a variable, then apply an *ngIf statement to the form to verify if the variable has a value.

component.ts

    public formData;
    ngOnInit() {
    this.route.params.pipe(mergeMap(params => {
      this.param1 = params['param'];
      this.hideForm();   //I want to implement this method
      return this.service.getInfo(this.param1);
    })).subscribe(data => {
      this.formData = data;
      this.formGroup.controls['title'].setValue(data.title);
      this.formGroup.controls['firstName'].setValue(data.firstName);
      this.formGroup.controls['lastName'].setValue(data.lastName);
      this.formGroup.controls['email'].setValue(data.email);
    }, err => {
      //in the error case the form should stay hidden
    });
  }

template

<form [formGroup]="formGroup" (ngSubmit)="handleSubmit()" *ngIf="formData">
  <mat-form-field>
    <input matInput placeholder="Title" formControlName="title" required>
  </mat-form-field>
  <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>
  <mat-form-field>
    <input matInput type="Email" placeholder="Enter your email" formControlName="email" required>
  </mat-form-field>
</form>

Answer №2

You could consider implementing an isLoading variable within the component, paired with an *ngIf directive to toggle the visibility of the form.

For example:

<form *ngIf="isLoading" [formGroup]="formGroup" (ngSubmit)="handleSubmit()">

(and make sure to set isLoading to true or false accordingly in your ngInit function)

Answer №3

To ensure that data is available before rendering, you can utilize the ngIf directive on the form element or its wrapper, triggering the evaluation only when the data is ready.

Alternatively, you can leverage the Router's functionality to navigate to a specific route once certain data is accessible. For more details, check out:

Wait for Data Before Rendering Views

The right way to prefetch data for your angular components

Load All Data Before Loading The Component View In Angular 6

... and more.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Guide to testing template-driven forms in Angular 6

Currently, I am working on a template-driven form which looks like this: <form #form="ngForm" (ngSubmit)="onSubmit()"> <input class="form-control input-lg" id="venue_name" name="venue_name" type="text" #venue_name="ngModel" [(n ...

Tips for emphasizing active tabs in Angular 6

**I have everything displaying perfectly, but I am wondering how to highlight the active tab without using any third-party components. Any assistance would be greatly appreciated. Thank you.** <ul class="tabs"> <li [ngClass]=" {'active-tab ...

angular2-highcharts series highlighting feature

I am working with an angular2-highcharts chart and I am trying to highlight specific lines of a data series when clicked. However, when using the code below, I encounter an error message that says Cannot read property 'series' of undefined. T ...

Dealing with mistakes in an Angular service

I've been grappling with error handling in Angular. I attempted to handle errors within a service, but I'm uncertain if that's the correct approach. @Injectable({ providedIn: 'root', }) export class CaseListService { public con ...

Experiencing an error when attempting to pass strings from .env.local to a new Redis instance

Encountering an issue with TypeScript while setting up a new Redis instance. I have configured an .env.local file with matching names for the redis URL and token. Below is the code snippet: import { Redis } from "@upstash/redis"; // @ts-ignore ...

MUI Autocomplete refuses to accept a value

In my Autocomplete feature, I have a list of all users available. When a user clicks on a button from another site, they are redirected to this site and the user's ID is fetched. I want the user with the corresponding ID to be automatically selected, ...

"I am experiencing an issue with the PrimeNG year picker as it is unable

My goal was to set up a simple PrimeNG calendar with just a year picker. I followed the implementation instructions from the documentation: <p-calendar inputId="year" [(ngModel)]="date1" view="year" dateFormat=" ...

In React Native, you can pass native component properties as props, while also defining custom ones using a TypeScript interface

I am working on a component called AppText where I need to utilize a Props interface and also be able to accept additional props that can be spread using the spread operator. However, I encountered this error: Type '{ children: string; accessible: tru ...

Angular ngFor Directive Failing to Display Menu Item Information on Right-Click Context Menu

Currently encountering an issue with implementing a right-click function in my context menu. The menu items are not appearing due to the second ngFor="let row" condition... however, I require the selected row object from a right click to pass in a JSON val ...

What is the best way to transfer a value from a parent component to a directive within Angular 2?

In the parent component, I currently have this line of code: <input datepicker type="text" (change)="update($event)"/> Is there a way for me to provide a value to the datepicker directive? ...

What is the best approach for retrieving a User from my Angular front-end service?

INQUIRY: I'm attempting to retrieve the details of the currently logged in user in my Angular 2 frontend service with the following code: UserModel.findById(userID, function (err, user) { It appears that this behavior is achievable from the browse ...

Exploring the power of nested components within Angular 2

I am encountering an issue with a module that contains several components, where Angular is unable to locate the component when using the directive syntax in the template. The error message I receive states: 'test-cell-map' is not a known elemen ...

How to dynamically retrieve values from a const object literal using TypeScript

Currently, I am utilizing a TypeScript library known as ts-proto, which is responsible for generating TypeScript code. The resulting generated code resembles the following: //BasicMessage.ts export interface BasicMessage { id: Long; name: string; } ...

What is the process for defining a default value for a template-driven form input in Angular 2?

I have a simple input element in my form that requires a default initial value to be set. <input type="number" name="interest_rate" [(ngModel)]="interest_rate"> In my code, I included this.form.controls['interest_rate'].patchValue(this.a ...

Updating a unique field with the same value causes a failure in the TypeORM update process

I am working with a service model in TypeORM, where I have a field called service_name that must be unique. However, when I attempt to update the table with the same value for service_name, it triggers a unique constraint violation error. I'm puzzled ...

"Customizing API requests based on specific conditions with n

For a specific scenario, I need to login as an admin in one case and as a regular user in another. signIn$ = createEffect(() => this.actions$.pipe( ofType(AuthActions.signInRequest), exhaustMap(({ variables, redirectTo, hasAdmin }) =&g ...

Restricting a checkbox to a maximum of 5 checkmarks

In a multi-column table, each column is represented by a checkmark. I want to limit the ability to tick a checkmark to only 5 checkmarks. Here is the code that has been implemented: <tbody> <ng-container *ngFor="let col of testData" ...

An issue arose when trying to display React components within an Angular application

Attempting to incorporate React components into an Angular 7 application has been a challenge for me. While I have successfully rendered simple React components, I encountered the following error message (displayed in the browser console) when attempting t ...

Unable to resolve the FormGroup when using the FormBulider

Currently, I am facing an issue while working with FormBuilder and FormGroup in Angular 2. When I try to submit a form, the form.value that is passed is of type FormGroup. After trying to access my properties and then restarting the lite server, the app f ...

Immer along with a subclass of Map

Recently, I decided to implement useImmerReducer in my React application for the first time, but encountered an issue. In my project, I utilize a custom class called Mappable, which is derived from Map: import { immerable } from "immer"; type K ...