顯示具有 Forms 標籤的文章。 顯示所有文章
顯示具有 Forms 標籤的文章。 顯示所有文章

2019年10月4日 星期五

To reset the form after submit

Usually, we expect that after we submit a form, the information entered will be cleared.

In Angular, we set up the method we design for addpost, the thing we need to do is to call the form.resetForm. The whole post-create component would be like this:


import { Component, OnInit, } from '@angular/core';
import { NgForm } from '@angular/forms';
import { PostsServiceService } from '../posts-service.service';

@Component({
  selector: 'app-post-create',
  templateUrl: './post-create.component.html',
  styleUrls: ['./post-create.component.css']
})
export class PostCreateComponent implements OnInit {

  enteredContent = "";
  enteredTitle  = "";

  onAddPost(form: NgForm){
    if(form.invalid){
      return;
    }

  this.postService.addPost(form.value.title, form.value.content);
  form.resetForm();
  }
  constructor(public postService: PostsServiceService) { }


  ngOnInit() {
  }

}