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() {
  }

}

沒有留言:

張貼留言