The reset function in Angular's template-driven form does not seem to be functioning properly when implemented using a component

Form Template Example

<form #contactFormTemplate = "ngForm" (ngSubmit)="submitContactForm()">        
       <input type="text" class="form-control" name="name" [(ngModel)]="formData.name">
       <!-- {{name!.value}} -->
       <button class="btn btn-primary mr-2" type="submit" 
       [disabled]="this.contactFormTemplate.status != 'VALID'">Submit</button>
       <a class="btn btn-secondary" (click)="clearForm()">Clear All</a>
    </form>

Form Component Class

export class FormComponent implements OnInit {
 
  constructor() { }

  ngOnInit(): void {
  }

  formData: any = {
    name: "",
  };

  submitContactForm() {
    console.log(this.formData); //form values
  }

  clearForm() {
    this.formData.reset(); // not working as intended
  }

}

Answer №1

Here is the solution to reset the form:

In TypeScript file

 clearAll(InputFormValue: ngForm) {
   InputFormValue.form.reset();//this code will clear the form
  }

In HTML file

<form #formGroupContactUs_Template="ngForm" (ngSubmit)="contactUsTemplateSubmit(formGroupContactUs_Template)">        
       <input type="text" class="form-control" name="name" [(ngModel)]="model.name">
       <!-- {{name!.value}} -->
       <button class="btn btn-primary mr-2" type="submit" 
       [disabled]="this.formGroupContactUs_Template.status != 'VALID'">Submit</button>
       <a class="btn btn-secondary" (click)="clearAll(formGroupContactUs_Template)">Clear Form</a>
    </form>

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

How to activate the close function of ionic-datepicker when tapping the hardware back button in Ionic 4

Utilizing ionic-datepicker in my app (ionic v-4), here is the corresponding template: <ion-datetime formControlName="meeting_date" display-format="MMM DD, YYYY"></ion-datetime> The datepicker (i.e ion-datetime) closes upon clicking cancel/do ...

React slick slider not functioning properly with custom arrows

"I have encountered an issue while trying to implement multiple sliders in my component with custom arrows positioned below each carousel. Despite following the documentation meticulously, the arrows do not respond when clicked. What could possibly be ...

Angular appears to be having trouble with localStorage functionality

Having an issue with my service that interacts with a local NOTES object array using localStorage. Whenever the page refreshes, the previously entered data is lost and only the initial data in the const NOTES array remains. Can't seem to figure out wh ...

Differences between `typings install` and `@types` installation

Currently, I am in the process of learning how to integrate Angular into an MVC web server. For guidance, I am referring to this tutorial: After some research and noticing a warning from npm, I learned that typings install is no longer used. Instead, it ...

What is the best way to have Vue i18n fetch translations from a .json file during Unit Testing?

Previously, with vue-i18n (v8.25.0 and vue v2.6.14), I stored all translations in .ts files containing JS objects: import { LocaleMessages } from 'vue-i18n' const translations: LocaleMessages = { en: { test: 'Test', }, } expor ...

Add a class to a button in an Angular btn-group if a specific string is found within an

I am currently working on a project where I have multiple buttons that need to toggle an active class when selected in order to change their color. Below is a snippet of what I have: In the array called 'selected', I have: this.selected = [&ap ...

What should be the proper service parameter type in the constructor and where should it be sourced from?

Currently, I am faced with a situation where I have two Angular 1 services in separate files and need to use the first service within the second one. How can I properly type the first service in the constructor to satisfy TypeScript requirements and ensure ...

When using the imported function, a TypeError occurs: "... is not recognized as a valid function."

I often use a function across multiple files, and it works perfectly like this: import moment from 'moment'; let monthAsString = (month: number): string => { return moment().locale('de').month(month - 1).format("MMMM"); } config ...

Create a new ASP.NET MVC project and integrate Angular 2 for a dynamic web application

I'm currently delving into the world of Angular 2 with Typescript. The primary resource I am using is QuickStart with Angular 2. From this and other examples, it has been emphasized to create a package.json file that outlines all dependencies for th ...

Angular Typed Forms Cannot Assign Values to Incomplete Types

I have created a simple example to demonstrate the goal I am trying to achieve: In essence, there are two types defined as follows: type BaseType = FormGroup<{ user: FormControl<string>; }>; type SomeOtherType = FormGroup<{ user: FormC ...

Angular 7+: Trouble with displaying images from assets directory

Details regarding my Angular version: Angular CLI: 7.3.9 Node: 10.15.3 OS: win32 x64 Angular: 7.2.15 ... animations, common, compiler, compiler-cli, core, forms ... language-service, platform-browser, platform-browser-dynamic ... rout ...

utilize a modal button in Angular to showcase images

I am working on a project where I want to display images upon clicking a button. How can I set up the openModal() method to achieve this functionality? The images will be fetched from the assets directory and will change depending on the choice made (B1, ...

How to import an HTML file using TypeScript

I need to load an html file located in the same directory as the typescript file and return it from the function. public ...(... ) : angular.IHttpPromise<string> { ... return $http({ method: 'GET', url: &apos ...

What is the method for implementing two-way binding on a checkbox in Angular?

Within my accordion, I have a series of options in the form of checkboxes. Users are able to select these checkboxes, but I am seeking a way to pre-select certain checkboxes based on specific conditions. The challenge arises when these conditions are deter ...

Building a filter for a union type in TypeScript: a step-by-step guide

Allow me to present an example to demonstrate my current objective. const v1: { type: "S"; payload: string } = { type: "S", payload: "test" }; const v2: { type: "N"; payload: number } = { type: "N", payload: 123 }; type Actions = typeof v1 | typeof v2; ...

Update an array while monitoring for a specific event

Working with Ionic, my goal is to push an array of an object when a specific event is emitted. This is what I currently have: export class PublicationService { constructor(private storage: Storage) {} private addPublicationSubject = new Be ...

The loginError variable in the ts file may experience a delay in updating its value

After entering an incorrect email and password, clicking on submit should set this.LoginError to return true in the component ts file console. However, it initially returns false, and only after clicking submit two or three times does the value finally upd ...

Prevent the Vue page from loading until the data has been fetched successfully

I'm in the process of finding a way to prevent my page from loading until my fetch task is completed. I'm facing some issues that need to be addressed: I have to re-fetch the data each time because I can't reuse the same data. (Changing vie ...

Deciphering a mysterious message in Typescript while defining a function for one of my tasks

Currently, I am working with a stack that includes React, TypeScript, and Redux. Unfortunately, I have encountered an issue while using an interface for one of my actions. The error message I received is quite cryptic: Duplicate identifier 'number&apo ...

Component in Angular not reloading when routerLink is clicked

When attempting to trigger a click event, I am unable to reload the component. The code snippet that I have tried is as follows: (dealCode,periodName) => { let url:any='/valuation;dealcode=J9PPR;fundPeriod=2019Q3;useDefault=true'; t ...