Intellipaat Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in Web Technology by (19.9k points)

In my Angular application I have a template-driven form with two-way binded input fields. If the submission fails, I want to display an error with a generic message. After the submission has finished and failed, the first thing I do is change the model used in the form. Then, I add an error to the form control.

After this, the form is updated with the new model values. But also, the error has been removed. So I guess it has been validated again at that point.

Below an edited simplified variant of the situation:

HTML Form

<form #form="ngForm">

    <div *ngFor="let vehicle of vehicles; let i = index">

      <span>{{ vehicle.name }}</span>

      <mat-form-field>

       <input

        name="odoInputVehicle{{ vehicle.id }}"

        required

        type="number"

        matInput

        min="0"

        [(ngModel)]="vehicle.distance"

        [disabled]="vehicle.submittable === false"

        />

      </mat-form-field>

   </div>

</form>

<mat-error *ngIf="this.form.control.hasError('submissionFailed')">

  <div>Error submitting the value(s).</div>

</mat-error>

Typescript code

@ViewChild('form', { static: false }) form: NgForm;

performRequests() {

  forkJoin(requests).subscribe(

    results => {

        // Result handling

    },

    error => {

        // Does something with the results

        // One or more requests failed

        // Model change

        succesResults.forEach(result => {

           this.vehicles[result.vehicleId].submittable = false;

        });

        // Apply an error to the form

        this.form.control.setErrors({

          submissionFailed: true

        });

    }

  );

 }

How can I add an error to the form that keeps being attached to the form after it also has changed the model. Is there an event to listen to that is fired once the model is updated that I can use for this?

1 Answer

0 votes
by (25.1k points)
edited by

you can use something like this:

<span *ngIf="this.form.control.errors" class="someClassREDTEXT">Form has error</span>

you check if there is an error with this.form.control.error and show the error message

Looking for a comprehensive Angular Course? Enroll now!

31k questions

32.8k answers

501 comments

693 users

Browse Categories

...