How can I automatically reset the input value within a formGroup in Angular 10?

Utilizing the angular form, I have created a search bar on the "search page" ("/search"). I've noticed that when I search for something, like "testing word", then navigate to the home page ("/") and return to the search page, the input in the search bar still shows "testing word".

I attempted using unsubscribe in ngOnDestroy, but it doesn't seem to work (ngOnDestroy is triggered based on the console log "haha"). While I know that resetting the searchTerm with a button click event would work, my goal is to automatically reset the values when leaving the search page. How can 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")
  }
}

Answer №1

If you call unsubscribe on this.searchSub, it will only stop listening to value changes you are subscribed to. Consider adding this.searchForm.reset() in ngOnDestroy to clear the form as well.

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

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Navigating through object keys in YupTrying to iterate through the keys of an

Looking for the best approach to iterate through dynamically created forms using Yup? In my application, users can add an infinite number of small forms that only ask for a client's name (required), surname, and age. I have used Formik to create them ...

Customizing data input in ngx chart's bubble chart is essential for creating a unique

For my project, I utilized the ngx-chart bubble chart. However, I encountered an issue when the data was in the following format: multi: any[] = [{ "name": "Kuwait", "series": [{ "name": "a", "waiting time": 24, "real time": 38, "queue size": 31 }, { " ...

Issue with decimal calculations in Angular 6 when using different LOCALE_ID settings

Currently, I am working on performing mathematical calculations involving decimals. In order to carry out these calculations, I have multiple inputs that interact with each other. These inputs represent the prices of different items. To ensure clarity in ...

Issue with PrimeReact dropdown component not recognizing an array in TypeScript

Trying to incorporate the PrimeReact Dropdown component in a NextJs app with TypeScript. Encountering an error when attempting to select options from the dropdown list: "Objects are not valid as a React child (found: object with keys {name, code})" The b ...

Defining data types for vue-router meta section

Within my router.ts, I included some meta properties with a 'getter' that I plan to utilize when the component is loaded. { path: "attachments", name: "AdminJobsAttachments", meta: { navbarName: "Attac ...

The issue of Angular Service Broadcast not functioning as expected when integrated with routing

When I subscribe to an event in Service, I am able to access the emitted data in another component. However, when I attempt to route the page, the data is being set in ngOnInIt() but after the routing process starts, it reverts back to its default state. T ...

What is the best way to display a loading state while waiting for all Firebase data requests to be fully processed?

Hey there! I'm looking for some advice on how to display a loading indicator like this: https://i.sstatic.net/7luvR.gif while waiting for my Firebase data to load completely. I attempted to use <div *ngIf="!listOfFoodObject"> <img [src ...

Unusual problem with [(ngModel)] not updating after Apollo subscription

I've encountered a strange issue with [(ngModel)] while working on an Angular 5 project. I have set up a form with inputs that successfully connect to the database using Apollo for sending GraphQL queries and mutations. The issue arises in editing set ...

Enhancing Code: Eliminate Duplicates from an Array

I have a code that removes duplicates from an array, but I believe it could be improved for better elegance. Any suggestions? Interface Definition export interface SomeClass { version: number, typeDescription: string } Test Data someClasses: SomeCla ...

Material UI TreeView: Organize and present node data with multiple columns in a tree structure

const treeItems = [ { id: 1, name: 'English', country: 'US', children: [ { id: 4, name: 'Spring', country: 'Uk', ...

When implementing ReplaySubject in Angular for a PUT request, the issue of data loss arises

I seem to be encountering a problem with the ReplaySubject. I can't quite pinpoint what I've done wrong, but the issue is that whenever I make a change and save it in the backend, the ReplaySubject fetches new data but fails to display it on the ...

Eliminate spacing gaps between the loading bars in ngx-skeleton-loader for Angular

In my current project using Angular11 with material and ngx-skeleton-loader, I am facing an issue with styling loading bars. I am trying to remove all spacing between the bars, but setting the margin and padding to 0px does not completely eliminate the spa ...

Tips for creating a static header div with a fixed size and a scrollable body

Check out the code snippet below as a reference: <div class="main"> <div class="header"> Header<br> Header<br> Header<br> Header<br> Header<br> Header<br> Header<br> Header<br> Header<br> He ...

Make sure to add the .npmrc file when setting up a fresh Angular project

Currently, I am in the process of developing a command line application with node.js. This specific application is designed to utilize the ng new command from angular CLI. During the creation of a new angular project, dependencies are automatically install ...

Enhancing React Native View and other component properties using styled-components

Utilizing styled-components for styling in my React Native app using Typescript has been effective. I recently crafted a StyledComponent to style a View component, but encountered an error when attempting to extend the ViewProps: The type '{ children: ...

Navigating through unidentified object in Typescript

I'm working with an object that has an unknown format, specifically a users' CSV file. My task is to iterate through the keys to identify certain keys, such as phone numbers referenced as phoneNumbers1, phoneNumbers2, and so on in the .csv file. ...

Tips for populating class attributes from an Angular model

Suppose there is a Class Vehicle with the following properties: public id: number; public modelId: number; public modelName: string; Now consider we have an object that looks like this {id: 1, modelId: 1, modelName: "4"} What is the best way to assign e ...

Add information to an array by simply modifying the existing data that shares the same key/value pair

Currently, I am working on the front-end of a delivery web application. On one of the screens, I have implemented a Google map that allows the company owner to track their delivery riders in real-time. The process of implementing the map itself was quite s ...

Accessing external data in Angular outside of a subscription method for an observable

I am struggling to access data outside of my method using .subscribe This is the Service code that is functioning correctly: getSessionTracker(): Observable<ISessionTracker[]> { return this.http.get(this._url) .map((res: Response) => ...

Deriving a universal parameter from a function provided as an argument

My function can take in different adapters along with their optional options. // Query adapter type 1 type O1 = { opt: 1 } const adapter1 = (key: string, options?: O1) => 1 // Query adapter type 2 type O2 = { opt: 2 } const adapter2 = (key: string, opti ...