0

I have two components. A header and a search form. The header gives you a form to search for a recipe. When you submit the form, you are redirected to the search page that shows you your search results. This functionality works. However, while I'm on the search page I want to submit another search(from the header). The search page will not re-render and update to show the new search results.

header.component.ts

export class HeaderComponent {

  constructor(private router: Router) { }

  query!: any;

  startSearch() {
   this.query = ((document.getElementById('form-control me-2') as 
      HTMLInputElement).value);
   console.log("Query:", this.query);
   this.router.navigate(['/search', this.query])
  }
}

header.component.ts

<div class="nav-overlay uk-navbar-left uk-flex-1" hidden>
        <div class="uk-navbar-item uk-width-expand">
            <form class="uk-search uk-search-large uk-width-1-1" (ngSubmit)="startSearch();" >
                <input id="form-control me-2" class="uk-search-input" type="search" placeholder="Search..." autofocus>
            </form>
        </div>
        <a class="uk-navbar-toggle" uk-close="ratio:2" uk-toggle="target: .nav-overlay; animation: uk-animation-fade" href="#"></a>
    </div>

search.component.ts

export class SearchComponent implements OnInit, OnDestroy{
  searchSub!: Subscription;
  errorMessage: string = '';
  
    constructor(
        private searchService: SearchService,
        private route: ActivatedRoute
    ) { }

    results!: ISearchResults;
    query!: any;

    ngOnInit(): void {
        this.route.paramMap.subscribe(params => {
            console.log(params);
            this.query = params.get('query');
        });
        this.searchSub = this.searchService
            .search(this.query)
            .subscribe({
                next: results => {
                    this.results = results,
                        console.log("Search query : ", this.query);
                }
            }
        );
    }

    ngOnDestroy() {
        this.searchSub.unsubscribe();
    }
}
DC4572
  • 11
  • 2

1 Answers1

0

This is answered here. Basically ngOnInit() is not being called because the component is already initialized. Put the search inside you paramMap subscription, then your results get updated when the route params change.

ngOnInit(): void {
    this.route.paramMap.subscribe(params => {
        console.log(params);
        this.query = params.get('query');
        this.searchService
        .search(this.query)
        .subscribe({
            next: results => {
                this.results = results,
                    console.log("Search query : ", this.query);
            }
        });
    
    });
    
}
Hopey One
  • 1,681
  • 5
  • 10