简体   繁体   中英

Clear a form value in Angular

I have an Angular form that contains a select box. The select box has an onChange event which should trigger a method to clear an input field also found in the form however nothing seems to be working.

html

<div class="ui-g-12 ui-md-12">
    <div class="ui-g-6 ui-sm-12">
        <div class="input-container">
            <label for="identityTypeId">Identity document type*</label>
            <p-dropdown [options]="identityDocTypeArr"(onChange)="clearIDNumberField()" formControlName="identityTypeId" id="identityTypeId" placeholder="Select"></p-dropdown>
        </div>
    </div>
    <div class="ui-g-6 ui-sm-12">
        <div class="input-container">
            <label for="identityValue">Identity number*</label>
            <input id="identityValue" type="text" formControlName="identityValue" size="50" placeholder="0000000000000" (blur)="validateSouthAfricanID()">
        </div>
    </div>
</div>

TS

clearIDNumberField() {
    this.offerFormGroup.get("identityValue").reset(); 
}

My forms name is [formGroup]="offerFormGroup"

您可以使用setValue设置/清除输入值

this.offerFormGroup.controls['identityTypeId'].setValue("");

Hello skyDev it looks like your code

 clearIDNumberField() {
    this.offerFormGroup.get("identityValue").reset(); 
  }

is not working because your reference the correct name of the formControl which if I am correct should identityTypeId . Hence what is wrong is actualy the control name been referenced. That been said the code should

  clearIDNumberField() {
        this.offerFormGroup.get("identityTypeId").reset(); 
      }

instead of

clearIDNumberField() {
    this.offerFormGroup.get("identityValue").reset(); 
  }

It might have been of good help if you had posted the contents of your formGroup variable too, but all the try the above changes.

Try This,

   clearIDNumberField() {
     this.offerFormGroup.reset(); 
   }

You can clear the forms value, in this case all the controls that makes up the form:

clearIDNumberField() {
     this.offerFormGroup.reset(); 
   }

This will reset the form to normal.

You can Try below function

clearIDNumberField() {
 this.offerFormGroup.identityValue = ''; 
}

You can reset with:

this.offerFormGroup.get("identityValue").setValue('')

and

this.offerFormGroup.controls["identityValue"].setValue('');

您应该使用setvalue('')方法。

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