如何仅重置 angular 中的特定表单字段 5
How to reset only specific fields of form in angular 5
我在我的一个组件文件中创建了一个函数来重置表单(myform):
`onSubmit() {
if (this.myform.valid) {
console.log("Form Submitted!");
this.myform.reset();
}
}`
重置整个表单效果很好,但是否可以只重置部分元素并保持其他元素不变。
是的,您可以使用 this.myform.controls
访问控件
获取控件并在其上调用 reset()
试试这个:
this.myform.controls['comments'].reset()
试试这个:
clearForm() {
this.myForm.get('comments').reset();
this.myForm.get('name').reset();
}
并在您提交表单的地方调用此函数。
更新:
我刚遇到这个问题,虽然接受的答案有效,但它有一些 tslint 警告。我最终做了:
this.myForm.get('formControlName').setValue(null);
我正在使用 Angular 8.
如果您想对多个字段执行此操作,这也适用:
private controlNames = ['nameOne', 'nameTwo'];
this.controlNames.map((value: string) => this.myForm.get(value).setValue(null));
在你的html
<select formControlName="idSala" (change)="clearField(1)">
<option value="">Selecione uma sala</option>
</select>
<input type="text" formControlName="titulo">
<input formControlName="dataHoraInicial" type="datetime-local">
TS
clearField(value) {
if (value == 1) {
this.formularioDeAgendamentoSala.controls['titulo'].reset();
this.formularioDeAgendamentoSala.controls['dataHoraInicial'].reset();
}
}
动态删除 FormControl 值:
private _clearFormGroupControlValue(formControlName: string) {
this.formGroup.get(formControlName).setValue(null);
}
or
private _clearFormGroupControlValue(formControlName: string) {
this.formGroup.controls[formControlName].reset();
}
or
private _clearFormGroupControlValue(formControlName: string) {
this.formGroup.controls[formControlName].patchValue(null || '');
}
我在我的一个组件文件中创建了一个函数来重置表单(myform):
`onSubmit() {
if (this.myform.valid) {
console.log("Form Submitted!");
this.myform.reset();
}
}`
重置整个表单效果很好,但是否可以只重置部分元素并保持其他元素不变。
是的,您可以使用 this.myform.controls
访问控件
获取控件并在其上调用 reset()
试试这个:
this.myform.controls['comments'].reset()
试试这个:
clearForm() {
this.myForm.get('comments').reset();
this.myForm.get('name').reset();
}
并在您提交表单的地方调用此函数。
更新:
我刚遇到这个问题,虽然接受的答案有效,但它有一些 tslint 警告。我最终做了:
this.myForm.get('formControlName').setValue(null);
我正在使用 Angular 8.
如果您想对多个字段执行此操作,这也适用:
private controlNames = ['nameOne', 'nameTwo'];
this.controlNames.map((value: string) => this.myForm.get(value).setValue(null));
在你的html
<select formControlName="idSala" (change)="clearField(1)">
<option value="">Selecione uma sala</option>
</select>
<input type="text" formControlName="titulo">
<input formControlName="dataHoraInicial" type="datetime-local">
TS
clearField(value) {
if (value == 1) {
this.formularioDeAgendamentoSala.controls['titulo'].reset();
this.formularioDeAgendamentoSala.controls['dataHoraInicial'].reset();
}
}
动态删除 FormControl 值:
private _clearFormGroupControlValue(formControlName: string) {
this.formGroup.get(formControlName).setValue(null);
}
or
private _clearFormGroupControlValue(formControlName: string) {
this.formGroup.controls[formControlName].reset();
}
or
private _clearFormGroupControlValue(formControlName: string) {
this.formGroup.controls[formControlName].patchValue(null || '');
}