Refreshing Form after Saving in Angular 4

After clicking the Save button, I want to reset the form (addUserForm). I created a modal with a form to input user data. This form serves for both editing existing data and creating new data, with the flag 'Create' or 'Update' differentiating between the two. However, when I reload the page and open the modal to add a new user after editing an existing one, the edited data remains in the form.

Here is the onSaveUser function:

onUserSave(user: User){
    let newUser = {
        name: user.name,
        role: user.role,
        email: user.email,
        password: user.password,
    }
    if(this.flag == 'create'){
  this.addUserForm.reset();
        this.dataStorageService.storeUsers(newUser);
    }else{
        this.dataStorageService.editUser(this.userId, newUser);
    }
    this.modalRef.close();
    this.addUserForm.reset();
}

This is the HTML code of the component containing the form:

<div [@routerTransition]>
    <app-page-header [heading]="' users '" [icon]="'fa-users'"></app-page-header>

    <a style="margin-right: 15px; cursor:pointer; padding: 0px;" role="button">
    <span (click)="open(content, 'create')"> add Users </span>
        <i class="fa fa-user-plus" style="color: red;"></i>
         <ng-template #content let-c="close" let-d="dismiss">
                    <!-- pop up -->
            <div class="modal-dialog modal-lg" dir="rtl">
             <div class="modal-header ">
              <h4 class="modal-title" style="color:red;">add new user</h4>
              <button type="button" class="close" aria-label="Close" (click)="d('Cross click')">
              <span aria-hidden="true">&times;</span>
             </button>
            </div>
                            <!-- pop up body -->
            <div class="modal-body">
            <form [formGroup]="addUserForm" (ngSubmit)="onSubmit(t)" #t="ngForm">
             <div class="row">
               <div class="form-group" class="col-lg-6">
                    <label >   username  </label>
                    <input class="form-control text-line" type="text" id="name" formControlName="name"  [(ngModel)]='name' required/>
                    <br />

                    <label class="padd">  password  </label>
                <input class="form-control text-line" type="password" id="password" formControlName="password" [(ngModel)]='password' required/>
                  </div>

                <div class="form-group" class="col-lg-6">
                <label>  Email </label>
                <input class="form-control  text-line" type="email" id="email" formControlName="email"  [(ngModel)]='email' required />
                <br />

                </div>
                <!-- modal footer -->
            <div class="modal-footer">
            <button type="submit" class="btn btn-success" (click)="onUserSave(addUserForm.value,t);" style="margin: 20px;" [disabled]="!t.valid" > حفظ </button>
            <button type="button" class="btn btn-danger" (click)="c('Close click')"> cancel</button>
                    </div>
                    </form>
                        <br />

                    </div>
                </div>
            </ng-template>
        </a>

            <hr>

            <table class="table table-hover table-condensed text-center">
                    <thead >
                            <tr class="text-center" style="background-color: #eef4f7; ">
                                    <th > # </th>

                                    <th > username                                      </th>

                                    <th >
                                            email
                                    </th>

                                    <th >
                                            edit
                                    </th>

                            </tr>
                    </thead>
                    <tbody>

                            <tr *ngFor="let user of users">
                                    <td>
                                            #
                                    </td>

                                    <td>
                                            {{user.name}}
                                    </td>

                                    <td>
                                            {{user.email}}
                                    </td>

                                    <td>
                  &nbsp;
                  <i class="fa fa-pencil-square-o fa-lg" style="cursor: pointer; color:#008000;" (click)="open(content, 'update', user)"></i>                       </td>
                            </tr>
                    </tbody>
            </table>

Answer №1

Unfortunately, I couldn't execute your code due to a few missing components. However, you can easily reset the form by implementing the following:

..... (click)="onUserSave(addUserForm.value,t); addUserForm.reset()" .....

Answer №2

<form [formGroup]="organisationSignUp" novalidate (submit)="OrganisationSignUp()">
</form>

This is an example of how to reset form fields after processing in a component:

OrganisationSignUp(){
// process form
....
....
// After finishing processing, clear the form like so

this.organisationSignUp.reset();
}

Following these steps will allow you to easily reset and clear form fields after data processing.

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

Angular is programmed to actively monitor the status of elements for enabling or

Seeking a solution to determine if an element is disabled in an Angular directive. Have attempted with host listeners, but no success yet. Directive: @HostBinding('attr.disabled') isDisabled : boolean; @HostListener("disabled") disabled() { ...

Protecting Your Angular Application with the Angular App Shell Architecture

I have a significant project that utilizes Angular's App Shell Model combined with Angular MSAL.js (v2). One issue I am encountering is ensuring that the guard checks are invoked before the app shell is built, rather than just for the projects injecte ...

Difficulty in styling with ag-Grid in SharePoint Framework (SPFX) combined with Angular

I'm currently delving into the world of custom SharePoint Web Parts using SharePoint Framework (SPFX) in combination with Angular Elements. One roadblock I've encountered is that when trying to implement ag-Grid, the style definitions for the gri ...

What is the best option: rewriting conditions and rules in Virtual Host or .htaccess file?

Currently, I am utilizing apache 2.4 to host an angular2 application. Initially, I defined the rewrite rules and conditions within my virtual host configuration. However, now I'm contemplating whether it would be more advantageous to employ an .htacce ...

Having trouble incorporating a canvas created with html2canvas into the addHTML() method of jspdf

I am working on developing an application using angular5 and I am attempting to incorporate HTML by utilizing the jspdf.addHTML() function in conjunction with html2canvas. const content = this.vc_print_section.nativeElement; html2canvas(content).then(can ...

Tips for utilizing the forEach method in Angular 2 without relying on ngFor?

I recently started learning Angular 2 and I am trying to figure out how to access array details using a forEach loop and apply certain conditions on it. Once I make the necessary changes, I want to display this data using ngFor. In Angular 1, this was ea ...

Tips for creating cascading dynamic attributes within Typescript?

I'm in the process of converting a JavaScript project to TypeScript and encountering difficulties with a certain section of my code that TypeScript is flagging as an issue. Within TypeScript, I aim to gather data in a dynamic object named licensesSta ...

Ngb-xx is not a recognized chemical property

Attempting to implement ngb bootstrap in my Angular project has been challenging. Errors keep popping up for every ngb component I try to use. https://i.sstatic.net/jF1xV.png Here's a glimpse of my package.json: https://i.sstatic.net/utqX6.png and ...

Adding attributes to an input element in real-time

I am in the process of generating multiple input elements using an *ngFor loop, and for some of them I would like to include a data-bv-integer="true" attribute, while leaving it out for others. The decision of whether or not to include this attribute depen ...

TSLint HTML Report Summary

Currently working on generating an HTML report for the "TSLint" task. Successfully created a report for "JSHint" using a specific package after installation. Struggling to locate a similar reporter for TSLint. "npm install gulp-jshint-html-reporter --sav" ...

Guide to implementing fullpagejs with Angular 7 selectors

I have been working on an Angular 7 project with fullpagejs by Alvarotrigo. Everything seems to be functioning properly, but I am facing an issue where the content of my website is not visible because the color of fullpagejs covers it all. When I use norma ...

Can anyone offer any suggestions for this issue with Angular? I've tried following a Mosh tutorial but it's

Just finished watching a video at around 1 hour and 35 minutes mark where they added the courses part. However, I encountered an error during compilation. ../src/app/app.component.html:2:1 - error NG8001: 'courses' is not recognized as an elemen ...

How can I only accept one of two specific function signatures in Typescript and reject any others?

Looking for an answer from the community on Typescript, require either of two function signatures In my code, I am handling a callback where I need to either pass an error or leave the first argument as undefined and pass data as the second argument. To ...

Guidelines on declining a pledge in NativeScript with Angular 2

I have encountered an issue with my code in Angular 2. It works fine in that framework, but when I tried using it in a Nativescript project, it failed to work properly. The problem arises when I attempt to reject a promise like this: login(credentials:Cr ...

Cannot retrieve the array stored within my object

Trying to navigate my way through Angular as a newcomer (just transitioning from AngularJS) I'm working with an api call that returns an object containing a subdocument (array). The structure of the object returned by the api is: contact:{ first_ ...

Managing data from devices by using Ionic v2 along with the BLE Central plugin

Currently experiencing some difficulties when it comes to managing the device data of discovered peripherals. I am searching for some guidance on this matter. I can successfully scan for devices and my "success" callback functions without any issues. My g ...

Utilizing external JavaScript libraries in Typescript for integration with nodeJS

We've recently made the switch to using Typescript + Electron for developing a browser-based desktop application. However, we often encounter delays when loading external Javascript libraries. While typings helps with most of our needs, there are stil ...

Quick + Vue Router - Lazy Loading Modules

For my personal project, I am using Vite alongside Vue 3 and have integrated vue-router@4 for managing routes. Since all of my modules share the same set of routes, I created a helper function: import { RouteRecordRaw } from 'vue-router' import p ...

Angular: The property '**' is not found on the type 'Object'

Not too long ago, I embarked on a new Angular project where my setup involves Angular (the front-end) communicating with a node.js server (the back-end), which in turn might make requests to an api server or a mongo database when necessary. The tricky par ...

What is the reason behind TypeScript choosing to define properties on the prototype rather than the object itself?

In TypeScript, I have a data object with a property defined like this: get name() { return this._hiddenName; } set name(value) { ...stuff... this._hiddenName = value; } However, when I look at the output code, I notice that the property is on ...