如何在Angular 2中提交后清除表单

如何在Angular 2中提交后清除表单

在Angular 2中,它们是两种类型的形式。

  • Template-driven forms.
  • 反应性的形式。

在模板驱动的表单中,大部分内容将被填充到.html文件中。
在反应式表单中,大部分的功能和内容都将在.ts文件中执行。反应式表单的主要优点是,我们可以创建自定义的验证,第二个关键的优点是,当我们进行单元测试时,由于HTML代码是干净的,所以编写单元测试是比较可行的。

在模板驱动的方法中重新设置一个表单。

在模板驱动的方法中,我们需要从@angular/forms中导入NgForm,我们使用[(ngModel)]指令进行双向数据绑定,我们还应该在app.module.ts文件中从@angular/forms导入FormsModule。在下面一行中,输入格式已经出现。除此之外,当我们提到ngModel指令时,我们需要为输入类型添加名称属性。

import { FormsModule } from '@angular/forms';

在Reactive forms中,我们需要从@angular/forms导入FormGroup。

在各自的方法中导入上述模块后,angular forms模块提供了一个内置的方法,叫做reset()。我们可以使用该方法,我们可以重置表单。

例子:.html文件

// In .html file
<form #login="ngForm" (ngSubmit)="completeLogin(login)">
    <h3>Login Form</h3>
  <label for="name">Username :</label>
  <input type="text" [(ngModel)]="username" name="name" id="name">
    
  <label for="password">Password :</label>
  <input type="password"
        [(ngModel)]="password"
        name="name" 
        id="password">
    
  <button type="submit">Submit</button>
  
</form>

例子:.ts文件

import {NgForm} from '@angular/forms'
import { Component, OnInit } from '@angular/core';
  
@Component({
  selector: "app-login",
  templateUrl: "./login.html",
  styleUrls: [],
})
  
  
export class Sample implements OnInit{
  
constructor(){}
  
ngOninit(){
}
  
username='';
password='';
  
completeLogin(login :NgForm){
 // In .ts file
  
login.reset() 
// call this inbuilt method to reset the form
  
}
  
}

在反应式表单中重设表单:

例子:.html文件

<form [formGroup]="login" (ngSubmit)="completeLogin()">
     // In.html file
  <h3>Login Form</h3>
.
.  <label for="name">Username :</label>
  <input type="text" formControlName="username" id="name">
    
  <label for="password">Password :</label>
  <input type="password" 
         formControlName="password" id="password">
    
  <button type="submit">Submit</button>
</form>

例子:.ts文件

import {FormGroup, FormControl} from '@angular/forms' 
import { Component, OnInit } from '@angular/core';
  
  
@Component({
  selector: "app-signin",
  templateUrl: "./signin.html",
  styleUrls: ["],
})
  
export class Sample implements OnInit{    
// In.ts file
  
login:FormGroup;
constructor(){}
  
ngOninit(){
  
login=newFormGroup({
username:new FormControl(''),
password:new FormControl(''),
})
  
}
  
completeLogin(){   
  
this.login.reset();  
// calling this method will reset the method
   
}
  
}

输出:

如何在Angular 2中提交后清除表单?

提交表格后,输出结果将是。

如何在Angular 2中提交后清除表单?

Python教程

Java教程

Web教程

数据库教程

图形图像教程

大数据教程

开发工具教程

计算机教程