Search code examples
angularangular-forms

Input binded data stays in input until refreshed


So this is the situation: I have a form-add.component where I have two inputs (title & body) and I create post requests using it. But the problem is that whenever I click 'Add' button and/or click 'Back' button, the written data in the input fields is not destroyed. So whenever I open this component again, the data in the inputs are shown. What should I do in order for it to be destroyed when I click 'Back' button or simply when I 'Add' it.

Here is my code:

form-add.component.html

<div class="container">
      <button class="btn btn-primary pull-right"
      (click)="userService.goBack()">Back</button>
</div>

<div class="container">
  <h2>Add New Post:</h2>
</div>

<div class="forms container">
<form #postForm="ngForm" ngNativeValidate>
    <div class="form-group">
      <label for="title">Title</label>
      <input [(ngModel)]="formAddService.form.title"
      name="title"
      id="title"
      type="text"
      class="form-control"
      required
      >
    </div>
    <div class="form-group">
      <label for="body">Body</label>
      <textarea [(ngModel)]="formAddService.form.body"
      name= "body"
      id="body"
      cols="30"
      rows="10"
      class="form-control"
      required
      ></textarea>
    </div>
    <button type="submit" class="btn btn-success" [disabled]="!formAddService.form.title || !formAddService.form.body" (click) = "formAddService.addForm()">Add</button>

    <table class="table text-center mt-5">
      <thead>
      <tr>
        <p class="title font-weight-bold">
            {{formAddService.form.title}}
        </p>
        <p class="body font-weight-normal">
            {{formAddService.form.body}}
        </p>
      </tr>
      </thead>
    </table>
</form>
</div>

form-add.component.ts

import { Component, OnDestroy } from '@angular/core';
import { UserService } from 'src/app/shared/users.service';
import { FormAddService } from './form-add.service';

@Component({
  selector: 'app-form-add',
  templateUrl: './form-add.component.html',
  styleUrls: ['./form-add.component.css']
})

export class FormAddComponent {

  constructor(public formAddService: FormAddService,
              public userService: UserService) {
  }
}

form-add.service.ts

import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { MatSnackBar } from '@angular/material';
import { Form } from '../forms/form-interface';

@Injectable({
  providedIn: 'root'
})
export class FormAddService {
  form: Form = {
    id: 0,
    userId: 0,
    title: '',
    body: ''
  };

  constructor(private http: HttpClient, private _snackBar: MatSnackBar) { }

  addForm() {
    return this.http.post<Form>('https://jsonplaceholder.typicode.com/posts',
    this.form).subscribe(
      data => {
        console.log('POST Request is successful ', data);
        this.openSnackBar('Post has been successfully added !', 'Close');
      },
      error => {
        console.log('Error', error);
      }
      );
  }

  openSnackBar(message: string, action: string) {
    this._snackBar.open(message, action, {
      duration: 2000,
    });
  }

}

Solution

  • With ngModel, you save any change to your form variable when you enter information into your inputs. So to reset the input value, you need to reset your form.

    It may be done this way adding the following method into your FormAddService :

    resetForm() {
      this.form = {
        id: 0,
        userId: 0,
        title: '',
        body: ''
      };
    }
    

    When adding data, you can place it there :

    addForm() {
        return this.http.post<Form>('https://jsonplaceholder.typicode.com/posts',
        this.form).subscribe(
          data => {
            console.log('POST Request is successful ', data);
            this.openSnackBar('Post has been successfully added !', 'Close');
            this.resetForm();
          },
          error => {
            console.log('Error', error);
          }
          );
      }
    

    For the back button, you can add it into your userservice.goBack() method.