[英]How can I reset Angular Reactive Form
我尝试过但未能找到重置我的角度形式的方法。
有人可以帮忙吗?
<form #thisIsAForm>
<mat-form-field class="full-width">
<input matInput placeholder="Weather">
</mat-form-field>
</form>
<button mat-raised-button (click)="resetForm()">Reset</button>
export class Example{
@ViewChild('thisIsAForm') thisIsAForm;
resetForm() {
this.thisIsAForm.reset();
}
}
差不多! 为此使用反应形式:
<form [formGroup]="myForm">
<mat-form-field class="full-width">
<input matInput placeholder="Weather" formControlName="weather">
</mat-form-field>
</form>
<button mat-raised-button (click)="myForm.reset()">Reset</button>
export class Example{
myForm: FormGroup;
constructor(private fb: FormBuilder) {
this.myForm = fb.group({
weather: ''
});
}
// If the HTML code doesn't work, simply call this function
reset() {
this.myForm.reset();
}
}
<form [formGroup]="thisIsAForm" (ngSubmit)="onSubmit()">
<mat-form-field class="full-width">
<input formControlName="weather" placeholder="Weather">
</mat-form-field>
</form>
<button mat-raised-button (click)="resetForm()">Reset</button>
export class Example{
thisIsAForm: FormGroup;
constructor() {
this.thisIsAForm = new FormGroup(
weather: new FormControl('')
);
}
resetForm() {
this.thisIsAForm.reset();
}
}
在 Angular 8 中,如果你这样做
<form #form="ngForm" (ngSubmit)="process(form)">
process(form: NgForm) { ...
使用--prod
构建时会出现以下错误
“FormGroupDirective”类型的参数不可分配给“NgForm”类型的参数。
在(ngSubmit)
我所做的是将form
模板引用作为FormGroupDirective
注入,然后调用resetForm()
。
<form #form (ngSubmit)="process(form)">
@ViewChild('form', { static: false }) FormGroupDirective formDirective;
我认为您需要在 html 代码中添加 ngForm 指令,如下面提到的 stackbliz 示例还添加 name 和 ngModel ngControl 以形成元素。
在这里,我正在重置模板驱动的表单,而不会使表单变脏。
<form class="example-form" #charreplaceform="ngForm">
<mat-form-field class="example-full-width">
<input matInput #codepointSel="ngModel" (change)="createReplacementChar()" (keyup)="checkForNumber()"
required [(ngModel)]="charReplaceInfo.codePoint" name="code-point" placeholder="Code Point (Only number)"
[disabled]="isDisabled">
</mat-form-field>
<a (click)="refreshCharRecord(charreplaceform)">
<i class="material-icons">
loop
</i>
</a>
</form>
// in .ts
refreshCharRecord(form: NgForm) { // getting the form reference from template
form.form.reset(); // here we are resetting the form without making form dirty
}
清除表格及其错误状态(脏污,原始等)的最简单,最干净的方法
this.formName.reset();
有关此处表单读取的更多信息
https://angular.io/docs/ts/latest/guide/forms.html
要么
只需重置特定控件(在这种情况下为“单选按钮”)
this.myForm.get('radioButtonControl').reset()
对我来说,将 type="reset" 添加到重置按钮解决了问题
<button **type = "reset"** mat-raised-button (click)="resetForm()">Reset</button>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.