Angular 2 form with ng2-bootstrap modal component reset functionality

I have implemented ng2-bs3-modal in my Angular 2 application. I am now looking for a way to clear all form fields when the close button is clicked. Can anyone suggest the best and easiest way to achieve this?

html

<button type="button" class="btn-u pull-right margin-bottom-10" (click)="modal.open()"><span class="fa fa-plus" aria-hidden="true"></span> Invite User</button>

<modal #modal>
    <modal-header [show-close]="true">
        <h4 class="modal-title">Invite User</h4>
    </modal-header>
    <modal-body>
        <form class="form-horizontal" id='myForm' role="form" [ngFormModel]="InviteUserForm">
            <div class="input-group margin-bottom-20">
                <span class="input-group-addon"><i class="fa fa-user"></i></span>
                <input type="text" [(ngModel)]='inviteUser.username' class="form-control" ngControl="username" required>
            </div>

            <div class="input-group margin-bottom-20">
                <span class="input-group-addon"><i class="fa fa-envelope"></i></span>
                <input type="email" required [(ngModel)]='inviteUser.email' class="form-control" ngControl="email" pattern="[a-z0-9._%+-]+@[a-z0-9.-]+\.[a-z]{2,3}$">
            </div>

            <div class="input-group margin-bottom-20">
                <span class="input-group-addon"><i class="fa fa-glass"></i></span>
                <select [(ngModel)]='inviteUser.partnerId' class="form-control" ngControl="partner" required>
                    <option>Select one</option>
                    <option *ngFor="let partner of _partners" value={{partner.Id}}>
                        {{partner.Name}}
                    </option>
                </select>

            </div>
    
        </form>
        <button type="button" class="btn-u btn-u-default margin-right-5" data-dismiss="modal">Close</button>
        <button type="button" [disabled]="!InviteUserForm.valid" class="btn-u pull-right" (click)="Invite(inviteUser)" data-dismiss="modal">Invite</button>
    </modal-body>

</modal>

Answer №1

To handle the close button event and reinitialize the form object, you can implement the following code:

<button type="button" (click)="resetForm()" class="btn-u btn-u-default margin-right-5" data-dismiss="modal">Close</button>

In your TypeScript file:

resetForm(){
    this.inviteUser = new InviteUserForm(); // This action will clear all fields bound in HTML
}

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

Prevent toggle button from activating panel expansion

Is there a way to add toggle buttons to the description section of an expansion panel without triggering the expansion panel when interacting with the buttons? I have included an example here. ...

Sweetalert seems to have hit a roadblock and is not functioning properly. An error has been detected in its TS file

Currently, I am responsible for maintaining an application that utilizes Angular 7.0.7 and Node 10.20.1. Everything was running smoothly until yesterday when my PC unexpectedly restarted. Upon trying to run ng serve, I encountered the following error: E ...

Encountered an unexpected token error when executing karma-coverage in a project using TypeScript

I have been working on a simple Angular/Typescript project that includes 12 basic unit tests which all pass successfully. However, I am now looking to measure the code coverage of these tests. Despite trying different methods, I have not been able to achie ...

Styling with ngStyle and changing the background image

Having an issue with a component that has an @Input string value linking to an image. In my HTML file, I originally had: <div class="parallax" [ngStyle]="{'background-image': 'url({{parallaxImage}})'}"></div> This was not ...

What is the best way to determine the type of a static property in a TypeScript class?

I have a utility class containing various static methods: export default class MyHelper { private constructor() {} private static privateMethod() {} public static publicHelperMethod() {} } In my React component, I am using the publicHelperMet ...

The element you are trying to access, "noUiSlider," does not belong to the type "HTMLElement" and cannot be found

Running into a roadblock here. What mistake am I making? .... /// <reference path="../../../typings/tsd.d.ts" /> var slider:HTMLElement = document.getElementById('slider'); noUiSlider.create(slider, { start: +$input.val(), step: + ...

Angular: You cannot assign a type of 'void' to a parameter that expects either a UserCredential or a Promise containing a UserCredential

Upon attempting to initiate a new method following a successful registration, I encountered an error in Webstorm: The argument type 'void' cannot be assigned to the parameter type '(value: UserCredential) => UserCredential | PromiseLik ...

Dealing with the "net::ERR_CERT_DATE_INVALID" issue within Ionic 4

When sending an "http" request in Ionic4, the response neither falls under the success callback nor gets handled by the error handling block. It just keeps loading indefinitely. I need a solution to properly handle this error in Ionic4 (Client side). I at ...

Troubleshooting: Vue.js component events not being detected in TypeScript

I'm encountering an issue with receiving events from a barcode reader, which I heavily referenced from a GitHub repository. The problem lies in the fact that the events emitted by the BarcodeScanner component are not being captured by the enclosing c ...

The correct way to incorporate a global property into a component template (using Vue 3, Vite, TypeScript, and the Composition API)

The component's property is not functioning properly https://i.sstatic.net/qaUG9.png src/main.ts import { createApp } from 'vue' import languagePlugin from '@/plugins/languagePlugin' import App from './App.vue' const a ...

The error message TS2322 in MUI v5 states that the property 'fullWidth' is not found in the type 'IntrinsicAttributes & { theme: Theme; } & { children?: ReactNode; }'

As a user of MUI v5, I have implemented a straightforward FormControl as seen below. It is important to note that the property fullWidth is supported according to the official documentation. import React, { PropsWithChildren } from 'react' import ...

What causes the variation in typing behavior between specifying props directly on a component versus nesting them inside another prop?

Understanding the next component might be a bit tricky, so let's delve into it (Check playground): type Props<T> = { initValue: T, process: (value: T) => T } export const Input = <T,>({ initValue, process, }: Props<T>): ...

acquiring the main class instance within a function without relying on an arrow function

Within my Angular project, I have integrated a datatable with row grouping and row callbacks. Datatable Options openPositionDatatableOptions = { sDom: 'rt<"bottom"p>', ajax: (data, callback, settings) => { this.service.ge ...

Building a High-Performance Angular 2 Application: A Comprehensive Guide from Development to

Recently, I began developing an Angular2 project using the quickstart template. My main concern now is determining which files are essential for deployment on my live server. I am unsure about the specific requirements and unnecessary files within the qu ...

Load Order Possibly Disrupted by Arrival of Barrel Imports

When attempting to unit test my component, I keep encountering errors related to my import statements: Error: Cannot resolve all parameters for 'MyComponent'(undefined, FormBuilder). TypeError: Cannot read property 'toString' of undef ...

The template reference variable has not been defined

The issue I'm facing is related to the template reference variable #newSkill on an input field. When passed as a parameter in the addToSkill() method, it works perfectly fine. However, when used in the chooseSkill() method triggered by clicking list ...

What is the best way to document a collection of generic interfaces while ensuring that they adhere to specific

I am currently utilizing a parser toolkit called Chevrotain to develop a query language that offers users the ability to enhance its functionality. Despite having all the necessary components in place, I am facing challenges when it comes to defining types ...

Encountering a CORS error in my Angular application while attempting to access a locally hosted Node Express API

I've been struggling with a CORS issue and can't seem to find a solution. My Node API application was built using Express, and the consumer is a simple Angular application. I've tried various solutions such as using CORS and including header ...

Encountering an issue while trying to upgrade angular from version 8 to version 16. The error message states: "Unable to bind to 'something' as it is not recognized as a property of 'something'."

Currently in the process of upgrading an old Angular 8 project to Angular 16. The update has been completed, however, when compiling the project I am encountering multiple errors related to components not being able to bind to certain properties that are s ...

Why isn't useEffect recognizing the variable change?

Within my project, I am working with three key files: Date Component Preview Page (used to display the date component) useDateController (hook responsible for managing all things date related) In each of these files, I have included the following code sn ...