Angular2中设置表单控件dirty/touched及弹窗表单重置方案
解决Angular 2弹窗表单重置问题
我来帮你搞定这个弹窗表单重置的需求——关闭弹窗后重新打开,表单要回到初始状态,之前的错误提示也得消失。针对你用的模板驱动表单,咱们可以通过以下步骤实现:
1. 组件类中添加表单重置逻辑
首先,在组件里获取表单的引用,然后在关闭弹窗的方法里执行重置操作,同时重置绑定的变量:
import { Component, ViewChild, NgForm } from '@angular/core'; @Component({ selector: 'your-component-selector', templateUrl: './your-component.component.html' }) export class YourComponent { @ViewChild('f') userForm: NgForm; // 获取表单引用 asyncSelected: any; // 你的输入框绑定变量 _isClose: boolean = false; formResetToggle: boolean = true; // 你的弹窗显示判断方法 isPopupOpen(): boolean { // 这里是你的逻辑,比如返回!this._isClose或者其他条件 return !this._isClose; } close() { // 第一步:重置表单的控件值和状态(包括submitted、touched等) if (this.userForm) { this.userForm.reset(); } // 第二步:重置组件中的绑定变量,确保下次打开弹窗时输入框为空 this.asyncSelected = null; // 第三步:执行弹窗关闭的UI逻辑 this._isClose = true; // 可选:如果typeahead这类第三方组件状态没重置,用toggle强制重新渲染表单 setTimeout(() => { this.formResetToggle = false; setTimeout(() => { this.formResetToggle = true; }, 0); }, 0); } // 你的其他方法:save(), showErrorAlert(), changeTypeaheadLoading()等 }
2. 调整HTML中的表单错误提示逻辑
修改输入框的ngClass条件和错误提示的显示逻辑,确保只有在表单提交或控件被触碰时才显示错误,重置后这些状态会被清空,错误提示自然消失:
<div *ngIf="isPopupOpen()" [ngClass]="{'modal-pop-close': _isClose}" id="myModal" class="modal-pop"> <div class="modal-content-pop"> <span class="close" (click)="close()">×</span> <h4 class="modal-title pull-left center-text"><i></i> New User</h4> <form *ngIf="formResetToggle" class="form-horizontal" name="useronboardEditorForm" #f="ngForm" novalidate (ngSubmit)="f.form.valid ? save() : showErrorAlert('User name is required', 'Please enter user name');"> <div class="form-group-btn"> <label for="username" class="user-name">User Name</label> <br /> <input [ngClass]="{'has-success': (f.submitted || username.touched) && username.valid, 'has-error1' : (f.submitted || username.touched) && !username.valid}" [(ngModel)]="asyncSelected" [typeahead]="dataSource" (typeaheadLoading)="changeTypeaheadLoading($event)" (typeaheadNoResults)="changeTypeaheadNoResults($event)" (typeaheadOnSelect)="typeaheadOnSelect($event)" [typeaheadOptionsLimit]="2" typeaheadOptionField="userName" [typeaheadMinLength]="3" placeholder="Search Users" [disabled]="false" class="form-controlBtn usernameBtn" type="text" name="username" autocomplete="off" #username="ngModel" required > <!-- 如果有单独的错误提示文本,加上这个 --> <div *ngIf="(f.submitted || username.touched) && !username.valid" class="error-text"> User name is required </div> </div> <!-- 其他表单字段和提交按钮 --> </form> </div> </div>
关键原理说明
NgForm.reset():这个方法会把所有表单控件的值重置为初始状态,同时将表单的submitted、touched等状态重置为false,这样之前的错误提示条件就不满足了,错误会消失。- 重置绑定变量:因为
[(ngModel)]是双向绑定,表单重置只会改控件的值,不会更新组件里的asyncSelected,所以必须手动重置它,不然下次打开弹窗输入框会保留之前的值。 - 表单强制重渲染:如果用了typeahead这类第三方组件,单纯reset可能清不掉它的状态,通过切换
formResetToggle的值,让Angular销毁再重建表单,就能彻底重置所有状态。
内容的提问来源于stack exchange,提问作者Niranjan
相关产品推荐
相关产品推荐

