Refresh a reactive form in Angular Material

I'm facing a challenge with resetting my form after data submission. Everything is working except for validating the email format. Using this.form.reset() doesn't seem to resolve the issue.

https://i.sstatic.net/QRZEa.png

Any suggestions on how to solve this?

<form [formGroup]="forma" (ngSubmit)="agregarDomiciliario()" novalidate>
      <mat-form-field>
        <input matInput placeholder="Property value" formControlName="propertyValue">
        <mat-error *ngIf="forma.controls['propertyValue'].invalid">{{ errorPropertyValue() }}</mat-error>
      </mat-form-field>
      <div class="row">
        <mat-form-field class="col-md-6">
          <input matInput placeholder="Enter your email" formControlName="email">
          <mat-error *ngIf="forma.controls['email'].invalid">{{ errorEmail() }}</mat-error>
        </mat-form-field>
        <mat-form-field class="col-md-6">
          <input matInput placeholder="Enter your phone number" formControlName="phone">
          <mat-error *ngIf="forma.controls['phone'].invalid">{{ errorPhone() }}</mat-error>
        </mat-form-field>
      </div>
      <div class="row mt-4">
        <div class="col-md-6">
          <mat-checkbox class="small" formControlName="accepts">I accept the terms and conditions</mat-checkbox>
        </div>
        <div class="col-md-6 text-right">
          <button mat-raised-button color="primary" type="submit" [disabled]="!forma.valid">Get Quote <i class="fas fa-arrow-right ml-2"></i></button>
        </div>
      </div>
    </form>

forma: FormGroup;

  constructor(fb: FormBuilder) { 
    this.forma = fb.group ({
      propertyValue: [ '', Validators.required ],
      email : ['', [Validators.required, Validators.email] ],
      phone: [ '', Validators.required ],
      accepts : [ false, Validators.requiredTrue ]
    });
  }
  
  agregarDomiciliario() {
    console.log(this.forma.value);
    this.forma.setValue({
      propertyValue : [''],
      email: [''],
      phone: [''],
      accepts : false,
    });
  }

Answer №1

Your function triggered by the (ngSubmit) event is making an incorrect call to setValue. To ensure that your form aligns with the values initialized in your constructor, modify it as follows:

addDeliveryPerson() {
  this.form.setValue({
    propertyValue: '',
    email: '',
    phone: '',
    agrees: false,
  });
}

Alternatively, if you want to assign the values of propertyValue, email, and phone to an array containing a single empty string [''] instead of just an empty string ''.

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

Converting milliseconds into a date format

I am looking to change milliseconds into a string that displays the time duration. function convertMsToTime(ms) { return ('' + Math.floor(ms / 86400000) + 'd -' + Math.floor((ms % 10) / 60).toString().padStart(2, '0')); } ...

Updating a value in an array in Angular using the same ID

I have an array of buildings that looks like this: const buildings = [ { id: 111, status: false, image: 'Test1' }, { id: 334, status: true, image: 'Test4' }, { id: 243, status: false, image: 'Test7' }, { id: 654, stat ...

Determine the amount of time that can be allocated based on the attributes contained within the object

I am faced with a JSON structure like the one below: var meetings = [ { id: '1', start_time: "2020-11-15T08:30:00+00:00", end_time: "2020-11-15T14:15:00+00:00" }, { id: '2', start_time: &quo ...

Does it follow standard practice for Array.filter to have the capability to also perform mapping on an array of objects?

While experimenting with Array.filter, I made an interesting discovery. By forgetting to include an equality check, my array was unexpectedly mapped instead of filtered. Here is the code snippet that led to this result: const x = [{ name: 'user' ...

Handling click events on several elements in Angular

My Objective: I aim to implement a collapsible accordion feature on a webpage that expands and collapses upon clicking. The expansion is triggered by adding the class collapsible-panel--expanded. My Approach: For each item, I have set a click event as fo ...

Exploring ways to conduct a thorough scan of object values, inclusive of nested arrays

My goal is to extract all values from an object. This object also includes arrays, and those arrays contain objects that in turn can have arrays. function iterate(obj) { Object.keys(obj).forEach(key => { console.log(`key: ${key}, value: ${o ...

OneGraph and Graphql Codegen produce enums with numerical representations

After migrating my project's codebase from using the direct Headless Wordpress GraphQL endpoint to OneGraph for Google+Facebook Business support, I encountered an error related to apollo referencing the output codegen. Here is the specific error messa ...

What is the proper way to retrieve a constant variable within a return statement?

Here is the code I have written: const keyToDisplayMessage = 'REGULAR_HOME'; const cf = format( { accountName: this.accountName, }, this.pageData.sucessMessages.keyToDisplayMessage, this.$route.name ); return cf; The ...

The exclude option in Nest JS middleware does not prevent the middleware from running on excluded routes

I'm having an issue with excluding certain routes from the middleware. The .exclude option doesn't seem to be working as expected, as the middleware is still being applied to the excluded routes. Here is the code for the Middleware: https://i.st ...

Angular 6: Transform object and add to array

My service includes a method called getCategory() that retrieves categories from the server. The method looks like this: getCategory(): Observable<CategoryModel[]> { return this.http.get<CategoryModel[]> (this.productUrl) .pipe( ...

Converting a JSON file stored locally into a key-value pair array

There are occasions when it's necessary to utilize varying sets of values based on the user's selection. This could involve different languages for communication or different color schemes for aesthetics. Currently, I am working on implementing t ...

Create a custom component that wraps the Material-UI TextField component and includes default

I have been exploring React and had a question regarding wrapping a component like TextField from mui to add new props along with the existing ones. I attempted to do this but am struggling to figure out how to access the other props. Can anyone help me ...

Fixing Angular minification issue with class names within 5 minutes

Who has encountered the issue of minification affecting class names in Angular 5+ and knows how to resolve it? I have a few classes: class FirstClass { } class SecondClass{ } And a check-function like this: function checkFunction() { const isEqual ...

Determining if a component is nested within itself in Angular 6 is a crucial task

My goal is to develop a custom Angular component for a nested navigation menu with multiple levels. Below is an example of how the menu structure looks: app.component.html <nav-menu> <nav-menu-item>Section 1</nav-menu-item> <nav- ...

Error encountered in Typescript React: JSON API Object expecting a ":" when indexing

Using Axios in Typescript React to fetch API Data. Here is a glimpse of the JSON Data :https://i.sstatic.net/DCXTz.png Trying to access the number value at index 1.tokenAmount.uiAmount Currently attempting data?[1]["tokenAmount"]["uiAmount"], but encoun ...

What is the best way to convert a date to ISO 8601 format using JavaScript? Are there any built-in functions or methods in

Currently, I am using this function to set the duration: const setDuration = () => { const currentDate = new Date(); const newDate = new Date(currentDate.getTime()); const year = newDate.getUTCFullYear(); const m ...

Addressing Overlap Issues in Angular 7 with NGXS and Firestore

Currently, I have a process in place where I retrieve data from Firestore and then update the state with it. Additionally, I make use of the NGXS Storage Plugin. While everything is functional, it does appear to be redundant. My approach involves a combi ...

Is my implementation of this [^{}]+(?=}) regex pattern in TypeScript accurate?

Hey there! I'm currently working on extracting values that are inside curly braces "{value}". Do you think the regular expression [^{}]+(?=}) I am using is correct? let url = "/{id}/{name}/{age}"; let params = url.match('[^{\}]+(? ...

When attempting an Axios request, the backend method cannot be accessed

I am facing an issue when using Axios request to access a method in the backend. I am constrained by pre-existing code in both frontend and backend that limits how much I can modify or add. Frontend: const response = await axiosConfig.put<IReserved&g ...

How to retrieve the value of an input field in Angular from a different element

I have a mat-table where each row contains a mat-slide-toggle and a button. I am looking for a way to pass the value of the mat-slide-toggle to the button's click function as an argument. <ng-container matColumnDef="show waiting list"> <ma ...