How to reset the previously selected item in mat-autocomplete while form reset

76 views Asked by At

I have a dropdrown developed using mat-autocomplete. I am trying to reset the entire form written using reactive form on click of reset button, but the value in the mat-autocomplete field doesnt get reset and hence the form.controls.state.status is INVALID.

<div fxLayout="column" fxFlex="19.2%">
                    <label class="text">State</label>
                    <mat-form-field appearance="outline" [floatLabel]="'always'">
                        <input type="text" maxlength="2" matInput [matAutocomplete]="auto" formControlName="state" (blur)="searchBtnEnable()">
                        <mat-autocomplete autoActiveFirstOption #auto="matAutocomplete">
                            <mat-option *ngFor="let option of filteredOptions | async" [value]="option.itemCd">
                                {{option.itemCd}}
                            </mat-option>
                        </mat-autocomplete>
                        <mat-error *ngIf="loanSearchForm.get('state')hasError('forbiddenValues')">
                           Select value from dropdown 
                        </mat-error>
                    </mat-form-field>
                </div>


resetForm() {
    console.log("loanSearchForm", this.loanSearchForm);

    this.loanSearchForm.reset();

}
1

There are 1 answers

0
Nikhil Makwana On

You can reset the entire form, including the mat-autocomplete field, by using the reset method on the FormGroup and then manually clearing the mat-autocomplete field's input value like

resetForm() {
    this.loanSearchForm.reset();

    // Reset mat-autocomplete input
    const stateFormControl = this.loanSearchForm.get('state');
    stateFormControl.setValue(''); // Set the value to an empty string
}

I hope this helps!