submitting an angular form and resetting the values afterward

I've implemented the following Angular form and I want to clear the text field after submitting the form.

        <form #addcheckinform="ngForm" novalidate (ngSubmit)="addcheckinform.form.valid && saveScheduleCheckin(this.checkin)">
        
          <div class="form-group row">
            <label for="email5" class="col-sm-3 col-md-3 col-form-label">Contact
              No.</label>
            <div class="col-sm-9 col-md-9">
              <input type="text" name="contactno" #contactno="ngModel" class="form-control" required
                     [ngClass]="{'is-invalid':addcheckinform.submitted && contactno.invalid}" placeholder="Contact No." [(ngModel)]="checkin.contactno" />
              </div>
            </div>
          <button type="submit" class="btn btn-action btn-flat float-right"
                  [disabled]="!addcheckinform.form.valid">
              <i class="fas fa-paper-plane"></i> <span> Submit</span>
          </button>
        </form>

The code snippet above is from my component.ts file

@ViewChild(NgForm) addcheckinform: NgForm;

saveScheduleCheckin(a){
    this.resetForm();
}

resetForm() {
    this.addcheckinform.reset();
}

When I console log this.addcheckinform, it returns as undefined. How can I correctly reset my form in this case?

Answer №1

@ViewChild('addcheckinform') addcheckinform: NgForm;

Answer №2

To simplify the code, you can remove ViewChild and use the following approach that worked for me: Here is an example: Html:

<span (click)="onSubmit(addcheckinform)"> Submit</span>

In component.ts:

onSubmit(form:NgForm){

form.submitted=true;
form.reset();

}

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

Having trouble building the React Native app after adding react-native-vector icons?

A recent project I've been working on involved adding react-native-vector-icons using react-native 0.63.4. However, during the build process, I encountered an error when running the command npx react-native run-ios in the terminal. The warnings/errors ...

`ng-apexcharts` causing unit test failures

I've been working on integrating apexcharts and ng-apexcharts into my home component. While I was able to get it up and running smoothly, it seems to be causing issues with my unit tests. Despite researching possible solutions, I haven't been abl ...

Issue with Ionic 2's infinite scroll not triggering method on second scroll attempt

I utilized the ion-tab element to showcase a page (inboxitem) which encompasses ion-list and makes use of ion-infinite-scroll. The following code snippet resides in inboxitem.html <ion-content class="inbox can-swipe-list"> <ion-list> ...

Angular is unable to bind with 'dragula' because it does not recognize it as a valid property of 'ul'

I've been attempting to incorporate dragula into my Angular 2 application, but I'm struggling to get it functioning. This is what I have added in my app.module.ts file: import { DragulaModule, DragulaService } from 'ng2-dragula/ng2-dragula ...

Leveraging Observables in an Angular 2 component to broadcast data to multiple components

Is it possible to utilize Observables in components and which other components can subscribe to them? BugListComponent - The component is injected in the boot.ts file where all services are loaded (where bootstrap is located) import {Subject, BehaviorSub ...

Typesafe-actions for defining typings of async actions reducers

I'm currently facing a minor issue while using createAsyncAction from the library typesafe-actions (Typesafe Actions) and correctly typing them for my reducer function Below is an example of the action being created: export const login = createAsync ...

Omit assets in final version

During development (ng serve), I have specific assets like images and styles that I use. These assets are not needed in the production build as they are provided by a CDN. My requirements are: When using ng serve, I want to serve files from the folder . ...

Using TypeScript to specify a limited set of required fields

Can a custom type constraint be created to ensure that a type includes certain non-optional keys from an object, but not all keys? For instance: class Bar { key1: number key2: Object key3: <another type> } const Y = { key1: 'foo' ...

Error: Unable to load the parser '@typescript-eslint/parser' as specified in the configuration file '.eslintrc.json' for eslint-config-next/core-web-vitals

When starting a new Next.js application with the specific configuration below: ✔ What name do you want to give your project? … app ✔ Do you want to use TypeScript? … No / [Yes] ✔ Do you want to use ESLint? … No / [Yes] ✔ Do you want to use T ...

Angular2 - Transmitting validation information from parent component to child component input validation

I am currently developing an automatic word correction module using Angular2. Within my child component, I have set up an EventEmitter. import {Component, Input, Output, EventEmitter} from '@angular/core'; ... export class StudyThumbsComponent{ ...

Router-outlet not displaying any content

I'm encountering an issue with using routing inside mat-drawer. Strangely, it results in a blank page. However, when I comment out the router-outlet element, the page displays correctly. Does anyone have insight on why this is happening? P.S. When I ...

Avoiding Maximum Call Stack Size Exceeded in Observables: Tips and Tricks

After filtering, I have a list stored in the variable filteredEvents$: public filteredEvents$ = new BehaviorSubject([]); I also have a method that toggles the checked_export property and updates the list: public checkAll(): void { this.filteredEve ...

Discover a more efficient method for expanding multiple interfaces

Hey there, I'm having some trouble with TypeScript and generics. Is there a better way to structure the following code for optimal cleanliness and efficiency? export interface Fruit { colour: string; age: number; edible: boolean; } export inte ...

Please click twice in order to log in to Angular 16

Whenever I attempt to log in, I face the issue of having to click twice. The first click does not work, but the second one does. Additionally, an error message pops up: TypeError: Cannot read properties of undefined (reading 'name'). I am unsure ...

Issue with Material UI Table not refreshing correctly after new data is added

Currently, I am utilizing a Material-UI table to display information fetched from an API. There's a form available for adding new entries; however, the problem arises when a new entry is added - the table fails to update or re-render accordingly. For ...

What is the recommended approach for sending a null value to a mandatory property in a Vue.js component?

Setup: Vue.js (3.2) with Composition API, TypeScript, and Visual Studio Code File type.ts: export class GeographicCoordinate { latitude: number; longitude: number; altitude?: number; constructor(latitude: number, longitude: number, altitude?: num ...

Uploading files in Angular alongside other data within the same HTTP post request

Can a file be added along with other information in a single post? export class ProfileExtraData { public id: number; public fullName: string; public file: any } return this.httpClient.post<void>(`${this.apiBaseUrl}/save`, profileExtraD ...

Issue encountered when attempting to develop a countdown timer using Typescript

I am currently working on a countdown timer using Typescript that includes setting an alarm. I have managed to receive input from the time attribute, converted it using .getTime(), subtracted the current .getTime(), and displayed the result in the consol ...

Difficulty in connecting React to Node.js with the use of axios

Recently, I embarked on a project using React and Node to create an app that allows users to add people data to a database. The frontend is built with React and can be accessed at localhost:3000, while the backend, developed with Node, runs on localhost:33 ...

Issues with updating values in Angular form controls are not being resolved even with the use of [formControl].valueChanges

[formControl].valueChanges is not triggering .html <span>Test</span> <input type="number" [formControl]="testForm"> .ts testData: EventEmitter<any> = new EventEmitter<any>(); testForm: FromCo ...