输入绑定的数据将保留在输入中,直到刷新

时间:2019-07-17 08:47:56

标签: angular angular-forms

这是这种情况: 我有一个form-add.component,其中有两个输入(标题和正文),并使用它来创建发布请求。但是问题是,每当我单击“添加”按钮和/或单击“返回”按钮时,输入字段中的写入数据都不会被破坏。因此,每当我再次打开该组件时,都会显示输入中的数据。单击“返回”按钮或仅在“添加”按钮时要销毁它,该怎么办。

这是我的代码:

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,
    });
  }

}

1 个答案:

答案 0 :(得分:0)

使用ngModel,当您在输入中输入信息时,可以保存对表单变量的所有更改。因此,要重置输入值,您需要重置表格。

可以通过以下方法将以下方法添加到FormAddService中:

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

添加数据时,您可以将其放置在此处:

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);
      }
      );
  }

对于后退按钮,可以将其添加到userservice.goBack()方法中。