with reference(https://mcmap.net/q/554590/-how-to-reset-only-specific-fields-of-form-in-angular-5
) , I have 20 fields in form, If user click reset option I need to reset form exclude 2 fields, If am using this.form.reset() means it reset every thing, Any help appreciated
Just look at the onReset()
method. This code will reset everything except the name
and description
fields
formGroup: FormGroup = /* init the formGroup... */
onReset() {
this.formGroup.reset({
name: this.formGroup.get('email').value,
description: this.formGroup.get('description').value
});
}
You can iterate over the controls of a FormGroup
, and if the controls name matches the one in your exclude list, you don't reset it:
const exclude: string[] = ['formControlName1', 'formControlName2'];
Object.keys(this.form.controls).forEach(key => {
if (exclude.findIndex(q => q === key) === -1) {
this.form.get(key).reset();
}
});
You can provide a reset value to the reset function. Simply give the value of your two fields to it, and the rest should be empty.
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);
You can pass an object to the reset function with Key as the formControl and value as the value you would like the control to have on reset.
this.form.reset({
fomrControl1:value1,
formControl2:value2
});
If you want to change the behavior of the field such as disabled or enabled, just pass in an Object instead of a value. For example:
this.form.reset({
fomrControl1:{value:value1, disabled:true}, // disables this field on reset
formControl2:value2
});
I would keep those two inputs value, reset form and just patch those two again.
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]);
Hey make a function reset()
and reset the 18
fields by using syntax like below.
resetForm(){
this.form.controls.formField1.reset("");
this.form.controls.formField2.reset("");
.
.
this.form.controls.formField18.reset("");
}
Thank You.
I followed a shortcut I did reset the full form Then I patched the value for a control which doesn't need a reset. Refer the snippet below
onCancelClick(form: NgForm) {
form.resetForm();
Object.keys(form.controls).forEach(name => {
if (name == "email") {
form.controls[name].patchValue(this.emailOfmember);
}
});
}
© 2022 - 2024 — McMap. All rights reserved.