[英]Reset angular reactive form exclude particular field
参考( https://stackoverflow.com/questions/50197347/how-to-reset-only-specific-fields-of-form-in-angular-5
),我有 20 个字段在表单中,如果用户单击重置选项我需要重置表单排除 2 个字段,如果我使用 this.form.reset() 意味着它会重置每件事,任何帮助表示赞赏
看看onReset()
方法。 此代码将重置除name
和description
字段之外的所有内容
formGroup: FormGroup = /* init the formGroup... */
onReset() {
this.formGroup.reset({
name: this.formGroup.get('email').value,
description: this.formGroup.get('description').value
});
}
您可以遍历FormGroup
的控件,如果控件名称与排除列表中的名称匹配,则无需重置它:
const exclude: string[] = ['formControlName1', 'formControlName2'];
Object.keys(this.form.controls).forEach(key => {
if (exclude.findIndex(q => q === key) === -1) {
this.form.get(key).reset();
}
});
您可以为重置功能提供重置值。 只需将您的两个字段的值赋予它,其余的应该是空的。
const resetValue = {};
for (const key of this.form.value) {
resetValue[key] = '';
}
resetValue.firstFieldToKeep = this.form.get('firstFieldToKeep').value;
resetValue.secondFieldToKeep = this.form.get('secondFieldToKeep').value;
this.form.reset(resetValue);
您可以将一个对象传递给重置函数,将 Key 作为 formControl,将 value 作为您希望控件在重置时具有的值。
this.form.reset({
fomrControl1:value1,
formControl2:value2
});
如果要更改字段的行为,例如禁用或启用,只需传入一个对象而不是值。 例如:
this.form.reset({
fomrControl1:{value:value1, disabled:true}, // disables this field on reset
formControl2:value2
});
我会保留这两个输入值,重置表单并再次修补这两个值。
const keepValues = [
this.form.controls.keepThis1.value,
this.form.controls.keepThis2.value,
];
this.form.reset();
this.form.controls.keepThis1.patchValue(keepValues[0]);
this.form.controls.keepThis2.patchValue(keepValues[1]);
嘿,创建一个函数 reset() 并使用如下语法重置18
字段。
resetForm(){
this.form.controls.formField1.reset("");
this.form.controls.formField2.reset("");
.
.
this.form.controls.formField18.reset("");
}
谢谢你。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.