How to auto reset input value (formGroup) in angular 10?

Issue

I am using the angular form to make a search bar in the "search page" ("/search"). I notice if I have searched something, e.g "testing word". Then, I go to home page ("/") and
go back to the search page, the input of searching bar, "testing word" remains.

I thought I use unsubscribe in ngOnDestroy, but it seems not work (ngOnDestroy is called based on console log "haha"). I know if using button click event to reset the searchTerm will work. However, I would like to have the values reset automatically when we leave the search page. How do I achieve this?

Thank you.

<form [formGroup]="searchForm" novalidate>
  <mat-form-field floatLabel="never">
    <input matInput type="type" autocomplete="off" formControlName="search">
    <mat-placeholder>Search</mat-placeholder>
  </mat-form-field>
  <a mat-icon-button aria-label="Search" (click)="emitState()">
    <mat-icon>search</mat-icon>
  </a>
</form>

---------------

export class SearchComponent implements OnInit, OnDestroy
{
  searchForm: FormGroup;
  private searchSub!: Subscription;
  constructor(private formBuilder: FormBuilder) {
    super();
    this.searchForm = this.formBuilder.group({
      search: ['', []],
    });
  }

  ngOnInit(): void {
    const searchTerms = this.values[0].value as string;
    this.searchForm.get('search')?.setValue(searchTerms);

    this.searchSub = this.searchForm.controls.search.valueChanges
      .pipe(debounceTime(400), distinctUntilChanged())
      .subscribe(
        (term) => {
          this.values[0].value = term;
          this.emitState();
        },
        (err) => console.log(err)
      );
  }

  ngOnDestroy(): void {
    this.searchSub.unsubscribe();
    console.log("haha")
  }
}

Solution

Calling this.searchSub.unsubscribe will only unsubscribe to the value changes that you are listing to. I think you should be able to add this.searchForm.reset() to your ngOnDestroy to clear the form.

ngOnDestroy(): void {
  this.searchSub.unsubscribe();
  this.searchForm.reset()
  console.log("haha")
}

Answered By – TheFlorinator

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published