I want to display the submission performed by the user after the form is submitted, by hiding the form area and showing the response in that area.
So on submitting the form,I'm supposed to show a mat-spinner until the response is received from the server.
The code for component.html file is 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>
and the component.ts part is as follows:
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));
}
So problem is, when I submit the form, I am making a POST request to the server for sending the feedback. Now I want to show the feedback submitted by the user, but on clicking submit, it directly shows me the value that I have used in the form instead of using the values from the server, but after 2 seconds(I've set delay of 2 s for the server response) the same area gets updated with the values received from the server, which is the way I actually want it to work.
Now I want to avoid using the instant form values and want to wait for 2 s so that the spinner is also visible.
I suppose I explained question clearly.
You could simply declare a flag to hide or not this chunk of form.
<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
defines a template that won't be rendered by default. The rendering of loading
(the template) will be triggered by the *ngIf
.
The *ngIf
evaluates a second flag.
waiting
should be set to true
whenever the HTTP request is sent, and set to false
when the response arrives.
this.waiting = true;
this.feedbackService.submitFeedback(this.feedback)
.subscribe(
feedback => {
this.feedback = feedback;
console.log(feedback);
this.waiting = false;
}, err => this.waiting = false; // In case the HTTP request fails
);
Try it out.