Issue with updating the div to show the user's submission form in Angular is causing difficulties

After a user submits a form, I would like to display their submission by hiding the form area and showing the response in that same area.

Upon submitting the form, my goal is to show a mat-spinner until a response is received from the server.

The component.html code snippet looks as follows:

  <div fxFlex [hidden]="!submitted">
    <mat-list *ngIf="feedback">
      <mat-list-item>
        <h4>Your Submission</h4>
        <p matLine>Id: {{feedback.id}}</p>
        <p matLine>First Name: {{feedback.firstname}}</p>
        <p matLine>Last Name: {{feedback.lastname}}</p>
        <p matLine>Tel. Number: {{feedback.telnum}}</p>
      </mat-list-item>

    </mat-list>

    <div [hidden]="feedback">
      <mat-spinner></mat-spinner><h4>Submitting Form</h4>
    </div>
  </div>


Below is the corresponding component.ts part:

   this.feedbackService.submitFeedback(this.feedback)
    .subscribe(
      feedback => (this.feedback = feedback,
      console.log(feedback))

    );

This is the service file:

submitFeedback(feedback: Feedback): Observable<Feedback> {
    const httpOptions = {
      headers: new HttpHeaders({
        'Content-Type': 'application/json'
      })
    };

    return this.http.post<Feedback>(baseURL + 'feedback/', feedback, httpOptions)
    .pipe(catchError(this.processHTTPMsgService.handleError));
  }

When I submit the form, it displays the values I used in the form instantly instead of waiting for the response from the server. After 2 seconds (to simulate a delay), the area then updates with the correct values retrieved from the server, which is the desired behavior.

To avoid displaying instant form values and ensure the spinner is visible, I want to implement a 2-second wait time for the server response before updating the view.

I hope this explanation clarifies the question.

Answer №1

If you want to control the visibility of a section in your form, consider declaring a flag for it.

<div fxFlex [hidden]="!submitted">

    <mat-list *ngIf="!waiting && feedback else loading">
        <mat-list-item>
        <h4>Your Submission</h4>
        <p matLine>Id: {{feedback.id}}</p>
        <p matLine>First Name: {{feedback.firstname}}</p>
        <p matLine>Last Name: {{feedback.lastname}}</p>
        <p matLine>Tel. Number: {{feedback.telnum}}</p>
        </mat-list-item>

    </mat-list>

    <ng-template #loading>
        <div>
            <mat-spinner></mat-spinner><h4>Submitting Form</h4>
        </div>
    </ng-template>

</div>

ng-template creates a template that is hidden by default but can be shown using *ngIf.

The *ngIf checks another variable.
Set waiting to true when an HTTP request is made, and set it to false upon receiving the response.

this.waiting = true;
this.feedbackService.submitFeedback(this.feedback)
    .subscribe(
      feedback => {
            this.feedback = feedback;
            console.log(feedback);
            this.waiting = false;
      }, err => this.waiting = false; // Handle failed HTTP requests
);

Give it a try!

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

Issues with ng2-pdf-viewer arising in Angular versions 12 and above

Issue Detected If 'pdf-viewer' is an Angular component with the 'src' input, ensure it is included in this module. If 'pdf-viewer' is a Web Component, add 'CUSTOM_ELEMENTS_SCHEMA' to '@NgModule.schemas' of ...

Instructions on transferring information from the app.component to its child components

I am currently working with Angular 6 and I have a specific requirement. I need to send data retrieved from an external API in my app.component to other child components. Instead of repeatedly calling the common API/service in every component, I want to ma ...

Warning issued by npm: An error occurred in the tar file entry due to an invalid argument while trying to

While executing npm ci in my docker container, I encountered the following error: $ npm ci npm WARN tar TAR_ENTRY_ERROR EINVAL: invalid argument, fchown npm WARN tar TAR_ENTRY_ERROR EINVAL: invalid argument, fchown npm WARN tar TAR_ENTRY_ERROR EINVAL: inva ...

Problem with 'executeScript' function in InAppBrowser'

Trying to run scripts in my app using the executeScript method of InAppBrowser. Running on Ionic Framework v2, here is my code: browser.executeScript({ code: ` $(".rodape.geral table tbody tr:nth-child(2) td:nth-child(1) div:nth- ...

Error message "Webpack is encountering an issue stating you might require a suitable loader" appearing during React development using TypeScript

I've been struggling to set up a new project using webpack, react, and typescript. Despite my efforts, I can't seem to get it to work. I've experimented with the html loader and followed various tutorials to try and resolve the issue. Here ...

Leverage the exported data from Highcharts Editor to create a fresh React chart

I am currently working on implementing the following workflow Create a chart using the Highcharts Editor tool Export the JSON object from the Editor that represents the chart Utilize the exported JSON to render a new chart After creating a chart through ...

How do I properly type when extending Button and encountering an error about a missing component property?

Currently in the process of transitioning from MUI v3 to v4. My challenge lies with some Button components that are wrapped and have additional styling and properties compared to the standard Material UI Button component. Ever since upgrading to v4, I&apos ...

A guide to configuring the default date format as ('dd/mm/yyyy') using ng-bootstrap

html <label for="date">{{ "date" | translate }}</label> <input type="date" class="form-control checking-field" id="date"> Is there a way to display the date in the format ('dd/mm/yyyy') in this HTML code? ...

The JWT token contains a HasGroup parameter set to true, however, the roles values are missing from the claims

I recently made some changes to the group claims in my Azure AD app's token configuration. While I can see a value of hasGroup: true in my token, I am not able to view the actual list of groups. Can someone please assist me with this? "claims&qu ...

Issue with NestJS verification of AWS Cognito JWT: "Error: applicationRef.isHeadersSent function not recognized"

I have integrated AWS Cognito as the authentication service for my NestJS application. However, when accessing the endpoint without a JWT (unauthenticated), the server crashes and displays the error TypeError: applicationRef.isHeadersSent is not a function ...

Calculate the minimum, maximum, and average values within an array containing nested elements

I want to calculate the min, max, and average values for nested data that already have these values precalculated. Essentially, I'm looking for the average of averages, min of min, and max of max. I have a large dataset that includes the min, max, an ...

In TypeScript, what do we call a property that is accessed dynamically?

I have a reusable function that can be used on various properties of a custom type. Here's an example: interface MyType { prop1: string; prop2: number; } type MyTypeKey = keyof MyType; const testValue = ( obj: MyType, property: MyTypeKey, v ...

The FileReader's onload event handler does not seem to be triggering as expected

In short, my issue revolves around reading a csv file from an android device using JavaScript's FileReader. Although my code was functioning properly a month ago, upon revisiting it recently I discovered that the onload function no longer seems to be ...

It seems that the Angular2-google-maps library is having trouble with installation

Attempting to install the angular2-google-maps library is resulting in errors. The desired library can be found at: The specific error encountered is displayed here: https://i.stack.imgur.com/L2vOY.png Any assistance with this issue would be greatly app ...

Tips for parsing data arrays in HTML templates

I have three variables and I created an array where I pushed all these three variables in. In my HTML template, I am using a table. I tried using *ngFor but it is not working, and also attempted string interpolation which also did not work. Currently, I ...

What is the best method for combining two observables into one?

My goal is to initialize a list with 12 users using the URL ${this.url}/users?offset=${offset}&limit=12. As users scroll, the offset should increase by 8. I plan to implement infinite scrolling for this purpose. However, I am facing an issue with appen ...

A single pledge fulfilled in two distinct ways

My code ended up with a promise that raised some questions. Is it acceptable to resolve one condition with the token string value (resolve(token)), while resolving another condition with a promise of type Promise<string>: resolve(resultPromise); con ...

How can I determine if a user has reached the end of a non-scrollable div by utilizing HostListener and directives within Angular?

In my Angular project, I have designed a main layout using flex display with specific height and overflow settings. The main content div inside this layout has its own unique styling to ensure consistent appearance for any components inserted within it. By ...

I'm encountering an error stating that a property does not exist for Twilio.Response() while attempting to convert a Twilio CORS Node.js example to TypeScript. Can anyone shed

In my current project, I am converting a CORS Node.js example from Twilio's documentation into TypeScript. Here is the original Node.js code: exports.handler = (context, event, callback) => { const client = context.getTwilioClient(); const resp ...

Tips on reordering modules in typings.json

Utilizing typings for loading type definitions. In my project, I am utilizing bluebird as the promise implementation. The following lines are present in my typings.json: "Promise": "github:DefinitelyTyped/DefinitelyTyped/bluebird/bluebird.d.ts#dd328830ddd ...