如何在Angular2中清空所有输入字段?
在Angular 2中清空所有输入字段的方法
嘿,我来帮你搞定Angular 2里清空输入字段的事儿!结合你给出的HTML代码,我整理了几种实用的方法,你可以按需选择:
方法一:重置绑定的Model对象(最推荐)
这是最简洁的方式,如果你用了[(ngModel)]双向数据绑定,直接把绑定的model属性重置为空值就行。不过先提个小问题:你金额框里的"model.amountInput"应该是[(ngModel)]="model.amount"吧?先修正这个语法错误,双向绑定才能正常生效~
步骤如下:
- 在组件类里定义初始的model对象:
// 组件类中的代码 model = { description: '', amount: '' }; // 清空所有字段的方法 clearAllFields() { // 重置model为初始空状态,绑定的输入框会自动同步清空 this.model = { description: '', amount: '' }; }
- 在模板中添加一个按钮来触发这个方法:
<button (click)="clearAllFields()">清空所有字段</button>
这样描述框和金额框就会自动跟着model的变化清空啦~
方法二:通过模板引用变量操作DOM(适合无ngModel的字段)
如果像你的客户名称框那样没有用[(ngModel)],可以用模板引用变量结合ViewChild来直接清空输入框的值。不过注意要给每个输入框设置唯一的引用变量名(你原来的#refrence重复了,会导致冲突):
- 修改模板里的引用变量:
<!-- 描述框 --> <textarea type="text" #descriptionRef class="form-control" id="description" pattern="^[a-zA-Z0-9/. ]*$" required minlength="30" maxlength="250" [(ngModel)]="model.description" name="description" #description="ngModel"></textarea> <!-- 金额框 --> <input type="text" #amountRef class="form-control" id="amount" required minlength="2" maxlength="10" [(ngModel)]="model.amount" name="amount"> <!-- 客户名称框 --> <input type="text" #customerRef placeholder="Custo...">
- 在组件类中引入
ViewChild并编写清空方法:
import { Component, ViewChild, ElementRef } from '@angular/core'; @Component({ // 这里是你的组件元数据,比如selector、templateUrl等 }) export class YourComponent { @ViewChild('descriptionRef') descriptionRef!: ElementRef; @ViewChild('amountRef') amountRef!: ElementRef; @ViewChild('customerRef') customerRef!: ElementRef; model = { description: '', amount: '' }; clearAllFields() { // 清空绑定了ngModel的字段(也可以直接用方法一的重置model方式) this.model.description = ''; this.model.amount = ''; // 清空没有ngModel的客户名称框 this.customerRef.nativeElement.value = ''; } }
- 同样在模板里添加按钮调用
clearAllFields()方法即可。
方法三:利用模板驱动表单的reset方法
如果你的所有输入框都放在一个<form>标签里,还可以用NgForm的reset()方法一次性清空所有绑定了[(ngModel)]的字段:
- 给表单添加模板引用变量:
<form #myForm="ngForm"> <!-- 描述框 --> <textarea type="text" class="form-control" id="description" pattern="^[a-zA-Z0-9/. ]*$" required minlength="30" maxlength="250" [(ngModel)]="model.description" name="description" #description="ngModel"></textarea> <!-- 金额框 --> <input type="text" class="form-control" id="amount" required minlength="2" maxlength="10" [(ngModel)]="model.amount" name="amount"> <!-- 客户名称框(建议也加上ngModel和name,这样reset能生效) --> <input type="text" placeholder="Custo..." name="customer" [(ngModel)]="model.customer"> </form> <!-- 点击按钮直接调用表单的reset方法 --> <button (click)="myForm.reset()">清空所有字段</button>
这种方式非常省心,点击按钮后表单内所有绑定了[(ngModel)]的字段都会被重置为初始值。
内容的提问来源于stack exchange,提问作者Sudharsan Venkatraj
相关产品推荐
相关产品推荐

