2

I have Angular6 project. It has listing component and detail component. In listing component, I have a search box. When I search anything and based on that when redirecting to the detail page, I am assigning queryParams and when coming back I am preserving those queryParams. And it is working fine.

But again when I type anything in the search box, I want to update the URL with the updated search string that I have entered in the search box without reloading the page again, i.e... I want to keep the queryParams updated while changing the search-box input field.

listing.component.html

<div class="input-group">
    <input type="text" name="search" [(ngModel)]="search">
</div>
<div class="row" *ngFor="let List of Lists | searchFilter:search:'name' | paginate: { itemsPerPage: 25, currentPage: page }">
    <div (click)="editList(List.ListId)">{{List.name}}</div>  
</div>

listing.component.ts

ngOnInit(): void {
    this.search = this.activatedRoute.snapshot.queryParams['search'] || '';
}

editPrice(ListId: number): void {
    this.router.navigate(['lists/edit', ListId], { queryParams:
        { search: this.search }
    });
}

detail.component.html

<a [routerLink]="['/lists']" queryParamsHandling="preserve">Go Back</a>
Augustin R
  • 4,694
  • 2
  • 13
  • 38
Er Vipin Sharma
  • 1,979
  • 7
  • 19
  • 30
  • You want to update the Url without a page reload or relocate? https://stackoverflow.com/questions/8560617/how-to-change-url-in-browser-without-navigating-away-from-page – Reinstate Monica Cellio Aug 17 '18 at 11:02

2 Answers2

0

Lets say you want to update parameter id with anotherId:

import { Location } from '@angular/common';

constructor(
    private route: ActivatedRoute,
    private location: Location,

) { }


ngOnInit() {
        this.route.paramMap.subscribe(param => {
            this.id = param.get('id');
        });
  }


updateUrl(){

   let anotherId : number = '10'

   let cururl = this.location.path().replace(this.id, anotherId );

   this.location.go(cururl);
}
Akj
  • 6,086
  • 3
  • 23
  • 33
  • In my case, I have search variable bound with HTML search box... Then how should I replace search variable => this.location.path().replace(this.id, anotherId ); – Er Vipin Sharma Aug 17 '18 at 10:29
-1

Instead of activateRoute.snapshot, subscribe to activatedRoute.params

For Example:

 this.activateRoute.params.subscribe((data) => {
     this.search = data.search
     // Your search logic here
 });
khush
  • 1,937
  • 11
  • 27
  • In this you again need to call your function search which has the logic of searching @ErVipinSharma – khush Nov 19 '18 at 11:13