有人建议,我需要删除控制组,并创建一个新的,以重建表单为原则.我很难弄清楚最好的方式来做到这一点.我知道我需要在一个函数中包装表单,但是在构造函数中这样做时我遇到错误.
什么是重建控制组以完全重置表单的最佳方式?
class App { name: Control; username: Control; email: Control; form: ControlGroup; constructor(private builder: FormBuilder) { this.name = new Control('',ValIDators.required); this.email = new Control('',ValIDators.required); this.username = new Control('',ValIDators.required); this.form = builder.group({ name: this.name,email: this.email,username: this.username }); } onsubmit(value: any): voID { // code that happens when form is submitted // then reset the form this.reset(); } reset() { for (let name in this.form.controls) { this.form.controls[name].updateValue(''); this.form.controls[name].setErrors(null); } }}解决方法 RC.6
支持重置表单并保持提交状态.
console.log(this.form.submitted);
this.form.reset()
要么
this.form = new FormGroup()...;
更新
要更新一些仅在创建表单时初始化的内容,需要进行一些额外的测量
<form *ngIf="showForm" showForm:boolean = true; onsubmit(value:any):voID { this.showForm = false; setTimeout(() => { this.reset() this.showForm = true; }); }
Plunker example
原始< = RC.5
只需将创建表单的代码移动到一个方法,并在处理提交后再次调用它:
@Component({ selector: 'form-component',template: ` <form (ngsubmit)="onsubmit($event)" [ngFormModel]="form"> <input type="test" ngControl="name"> <input type="test" ngControl="email"> <input type="test" ngControl="username"> <button type="submit">submit</button> </form> <div>name: {{name.value}}</div> <div>email: {{email.value}}</div> <div>username: {{username.value}}</div>`})class FormComponent { name:Control; username:Control; email:Control; form:ControlGroup; constructor(private builder:FormBuilder) { this.createForm(); } createForm() { this.name = new Control('',ValIDators.required); this.email = new Control('',ValIDators.required); this.username = new Control('',ValIDators.required); this.form = this.builder.group({ name: this.name,username: this.username }); } onsubmit(value:any):voID { // code that happens when form is submitted // then reset the form this.reset(); } reset() { this.createForm(); }}
Plunker example
总结以上是内存溢出为你收集整理的提交后重新设置角度2中的表单全部内容,希望文章能够帮你解决提交后重新设置角度2中的表单所遇到的程序开发问题。
如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)