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