简体   繁体   中英

how to reset a form value in angular?

for Example there is a condition and I wanna reset the firstName value to null or empty is there something like

this.modelForm.get('firstName').clearField(); ? or this.modelForm.get('firstName').setValue == "" ?

thanks.

#Code

initFormGroup() {
    this.modelForm = this.formBuilder.group({
      id: [this.model.id || 0],
      emailAddress: [this.model.emailAddress, Validators.required],
      firstName: this.model.firstName,
    });
  }

You can do it easily with this.modelForm.reset() . It will restore the defaulut value of your form. Aslo you can only reset a control with this.modelForm.controls.firstName.reset()

You can apply reset to FormControl , FormGroup and FormArray since reset is declared in AbstractControl but each one has its own implementation.

In this case you can do:

this.modelForm.get('firstName').reset();

That will clear the value and mark the control as untouched.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM