Home > Software engineering >  Set RouterLink value dynamically after click
Set RouterLink value dynamically after click

Time:01-19

In the Angular application, there is a grid in which the first column is Name, and the routerLink value is decided based on the runtime API call and its return type. Shown below:

<tr *ngFor="let a of sliceList; trackBy: trackById">
      <td>
        <app-agency-state [Agency]="a"></app-agency-state><span>Name</span>
        <a [routerLink]="agencyLink(a)" style="cursor: pointer">{{a.name}}</a>
      </td>
</tr>

and in the agencyLink method, there is an HTTP call, and in its subscription, we will be returning the URL value. Seems logical but as we have hundreds of agencies and so during grid load, an HTTP call is getting triggered for all of the agencies and that puts browser in the hanged state. what could be the alternative solution to managing and deciding the RouteLink value dynamically after click?

CodePudding user response:

<tr *ngFor="let a of sliceList; trackBy: trackById">
  <td>
    <app-agency-state [Agency]="a"></app-agency-state><span>Name</span>
    <a [routerLink]="agencyLink(a)" (click)="updateAgencyLink(a)" style="cursor: pointer">{{a.name}}</a>
  </td>
updateAgencyLink(agency: any) {
// make API call and update agencyLink value
this.agencyLink = this.apiService.getAgencyLink(agency.id).subscribe(
  res => {
    this.agencyLink = res.url;
  },
  err => {
    console.log(err);
  }
);

CodePudding user response:

use navigationByUrl instead if routerLink

<a (click)="agencyLink(a)" style="cursor: pointer">{{a.name}}</a>

inject router in your component and in subscription result of method

this.router.navigateByUrl(result.url)

this can help

  • Related