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

When creating an async function, the type of return value must be the universal Promise<T> type

https://i.stack.imgur.com/MhNuX.png Can you explain why TSlint continues to show the error message "The return type of an async function or method must be the global Promise type"? I'm confused about what the issue might be. UPDATE: https://i.stac ...

Angular data binding between an input element and a span element

What is the best way to connect input texts with the innerHTML of a span in Angular6? Typescript file ... finance_fullname: string; ... Template file <input type="text" id="finance_fullname" [(ngModel)]="finance_fullname"> <span class="fullnam ...

Trouble arises when managing click events within the Material UI Menu component

I've implemented the Menu Component from Material UI as shown below - <Menu open={open} id={id} onClose={handleClose} onClick={handleClick} anchorEl={anchorEl} transformOrigin={{ horizontal: transformOriginRight, vertical: t ...

When making Angular GET requests, the response may return a single Object instead of an Array

When making a GET request to my API, the data is returned as Objects inside an Object instead of an Array of Objects. This makes it difficult for me to iterate through and print the data. I am puzzled by why this specific request is behaving differently c ...

Encountering TS2322 error when defining a constructor in Angular 2 with ag-grid

Currently, I am following a tutorial I stumbled upon online titled Tutorial: Angular 2 Datatable with Sorting, Filtering and Resizable Columns. It appears to be the most straightforward guide to help me get started with the ag-grid library before delving d ...

Retrieve the parent route component in Angular

I am in the process of developing an Angular 7 application that features nested routes. My goal is to identify the specific component being used by the parent route. While I have managed to achieve this locally, the method fails in a production environment ...

Encountering an undisclosed CORS error on all requests from Angular frontend to NodeJS Express Server during preflight 200

After thorough testing with Postman, my backend server is functioning properly and generating the desired responses for all requests. However, my Angular app is encountering an unknown CORS error on every request despite receiving a 200 Preflight response ...

A TypeScript array interface featuring an indexed structure along with the ability to access custom properties through string keys

I am looking to create an array of objects in which each object is indexed by numbers and can also be grouped under a specific key. Here's what I have so far: const myArray:ICustomArray = [] myArray.push(item) myArray[item.key] = item; However, I a ...

Cookies are not being sent by Angular 2

Currently, I am working on a project that involves frontend development using angular 2 and backend with symfony as the API. However, I am facing an issue where I need to send the PHPSESSID when making a request to symfony, but it is not happening as expec ...

Narrowing Down State Types

I am working on a functional component in NextJS with props passed from SSR. The component has a state inside it structured like this: const MyComponent = ({err, n}: {err?: ErrorType, n?: N})=>{ const [x, setX] = useState(n || null) ... if(e ...

What is the proper method for typing unidentified exports that are to be used in TypeScript through named imports?

Currently, I am developing an NPM package that takes the process.env, transforms it, and then exports the transformed environment for easier usage. The module is structured like this: const transformedEnv = transform(process.env) module.exports = transf ...

A practical guide to effectively mocking named exports in Jest using Typescript

Attempting to Jest mock the UserService. Here is a snippet of the service: // UserService.ts export const create = async body => { ... save data to database ... } export const getById = async id => { ... retrieve user from database ... } The ...

Iterate through each item in an object using Angular

I attempted to utilize a forEach loop, but it's indicating that it's undefined for some reason. Here is my code snippet: var array: MoneyDTO[] = prices array.forEach(function (money: MoneyDTO) { if (money.currency == 'QTW& ...

Issues with Typegoose and Mongoose Enums when utilizing an array of strings

One of my enums is defined as follows: export enum Careers { WEB_DEVELOPMENT = 'Web Development', MOBILE_DEVELOPMENT = 'Mobile Development', UI_UX = 'UI/UX' } This particular enum is used as a mongoose property like so: ...

Issue with type narrowing and `Extract` helper unexpectedly causing type error in a generic type interaction

I can't seem to figure out the issue at hand. There is a straightforward tagged union in my code: type MyUnion = | { tag: "Foo"; field: string; } | { tag: "Bar"; } | null; Now, there's this generic function tha ...

The live updates for user data in Firestore are not being reflected immediately when using valueChanges

Utilizing Angular and Cloud Firestore for my backend, I have a setup where users can follow or unfollow each other. The issue arises when the button text and list of followers/following do not immediately update on the front end after a successful click ev ...

Leveraging Shared Modules Component across multiple modules in Angular can enhance code re

In my project structure, I have a shared folder containing shared.module.ts. Additionally, there is a modules folder with sub-modules, one of which is Dashboard.module.ts. Inside the shared module, I created a custom sidebar menu that I intend to use withi ...

The Angular interceptor is highlighting an issue with the catchError operator

I'm currently working on creating an interceptor to manage HTTP errors in my Angular 10 project. Check out the code snippet below: import { HttpEvent, HttpHandler, HttpInterceptor, HttpRequest, HttpResponse } from '@angular/common/http'; imp ...

`In TypeScript Angular, encountering challenges with accessing object properties`

My TypeScript object looks like this const playlist: { tracks: Array<Track> } = { tracks: new Array<Track>() }; This is the Track interface I am working with interface Track { title?: string; album?: string; artists?: string; duration? ...

I'm facing difficulty in assigning props because of the specific nature of generics in Typescript

My goal is to create a Higher Order Component (HOC) that can control a component which relies on certain props to function properly. To elaborate: I want to build a HOC that takes a component expecting props value and onChange, and modifies it so that the ...