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

Using `querySelector` in TypeScript with Vue 3

Encountered a TypeScript error while using the Vue Composition API let myElement = document.querySelectorAll('my-element') The TS error I'm getting when trying to access it like this: Property '_props' does not exist on type ...

The count of bits is not producing the anticipated result

Attempting to tackle the challenge of Counting Bits using JavaScript, which involves determining the number of set bits for all numbers from 0 to N, storing them in an array, and returning the result Let me provide an explanation Input: n = 5 ...

Starting a new subscription once the current one expires

What is the process for starting a new subscription once an existing one ends using rxjs operators in Angular with 2 select statements? this.store.pipe( takeUntil(this.onDestroy$), select(getDatasetIsCreation), filter((datasetCreation) ...

The following 13 error occurred in the node_modules/next/dist/esm/server/web/spec-extension/cookies/serialize.js file

Every time I try to use the serialize function in my application on Next, it throws errors. Error - node_modules/next/dist/esm/server/web/spec-extension/cookies/serialize.js (40:0) @ parseCookieString Error - URI malformed I have attempted numerous soluti ...

Angular Material calendar tool customization for designated input

Is it possible to individually control the format of input for a datepicker without affecting the format for the entire module? <input matInput [matDatepicker]="dp" [formControl]="date" [format]="'DD/MM/YYYY'"> <-- Can this be done? < ...

Is it possible to stop Angular requests from being made within dynamic innerhtml?

I have a particular element in my code that looks like this: <div [innerHtml]="htmlContent | sanitiseHtml"></div> The sanitiseHtml pipe is used to sanitize the HTML content. Unfortunately, when the htmlContent includes relative images, these ...

What is the best way to access the original observed node using MutationObserver when the subtree option is set to

Is there a way to access the original target node when using MutationObserver with options set to childList: true and subtree: true? According to the documentation on MDN, the target node changes to the mutated node during callbacks, but I want to always ...

Can a ternary operator be used within an index type query when extending a partial type?

Can anyone provide a detailed explanation of the process unfolding in this snippet? I'm having trouble grasping how this code leads to a type declaration. type ModalErrors = Partial< { [key in keyof InputGroup]: InputGroup[key] extends Speci ...

Angular 4 has the capability to automatically log out in all tabs when a user logs out in one open tab

I am looking to implement a feature where I automatically log out from all open tabs when logging out from one tab. Currently, I am storing a jwt token in localStorage upon login and removing the token upon logout. Any suggestions on how I can utilize st ...

Having trouble with enzyme in React Typescript application

One of my components is called app.tsx import React, { useState } from "react"; const TestComponent = () => { return( <> <div className="head">hey there</div> <select name="xyz" id=&qu ...

Tips for adjusting the position of overflowing text on a website using CSS in real-time

I'm currently working on an Angular application and I'd like to customize the styling so that any text exceeding 128 characters is not displayed. Ideally, if the text exceeds 128 characters, it should move to the left; otherwise, it should remain ...

What is preventing this from being a function?

It appears that the authenticationProvider is missing for some reason. @autoinject() export class ProviderManager implements AuthenticationManager { constructor( private container: Container ){ } public authenticate( creds: Credentials ): Promis ...

Expanding the property of an established type to a nested type

Let's talk about titles. Well, maybe not this one. I tried to come up with a good title, but it didn't work out as planned. In my coding journey, I have created a cool interface called DefaultTheme: export interface DefaultTheme { colors: ...

Accessing HTTP data through a function instead of using ngOnInit in Angular is a more efficient approach

Trying to retrieve data from a service using setInterval has posed an issue for me. When I call the service from ngOnInit, everything functions as expected. However, when attempting to call it from any other function, an error occurs: "ERROR TypeError: Ca ...

Troubleshooting a Docker EPERM issue while attempting to compile an Angular application within a container

Our team is currently in the process of containerizing our existing stack using Docker and Docker Compose. This is a simplified version of our Docker Compose file with the relevant services: version: '3.8' services: #FO angularproject: c ...

Refine the category based on a specified key

Currently, I am in the process of developing a React Hook using TypeScript. In this hook, I am passing both a key and a value that will be associated with this key as arguments. My objective is to constrain the type of the value based on the specified key. ...

The Node.js application successfully operates on a local environment, however encounters issues when attempting to run on docker resulting in an error message stating "sh

Despite successfully building the docker image, I am facing difficulties getting the container to run. Below is the content of the package.json file: { "name": "linked-versions-viewer", "version": "1.0.0", &quo ...

Ways to transmit additional arguments to RxJS map function

When working with an Angular application, I utilize HttpClient along with RxJS operators to execute various API calls. One example of this is shown below: return this.httpClient.put(url, JSON.stringify(treeOptions)) .pipe( map(this.extract ...

Tips for assigning the 'store_id' value to a variable in Angular 6 within the Ionic4 environment

Trying to retrieve the store_id from the StorageService in Ionic4 (angular 6). Managed to retrieve the store_id using: let id = this.storageService.get('store_id'); id.then(data => { this.store.push(data) }); After pushing it into an ar ...

Setting a default value for a null Select Option in React: a guide

I am currently working with an array of values and looping through them to display in a Select Option. <Form.Item label="Status"> <Select value={user.status} onChange={handleStatusChange} > ...