menu

Questions & Answers

Set the routerlink value dynamically after click using HostListener

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>

We have hostlistener, where we trying to get the URL using an HTTP call, and also we want to set the routerlink value here only. And, we also need to get the current clicked value i.e. current agency object in Hostlistner. Is it possible or there is another standard way to achieve this?

@HostListener('click', ['$event'])
  onClick(event: MouseEvent) {
    this.agencyService.getArchive(a.id).subscribe(
      res => {
        a.href = `/dashboard/agenecy/archived/${a.id}`;
      },
      err => {
        a.href = `/dashboard/agency/${a.id}`;
      });
  }
Answers(1) :

You don't need to always use routerLink to perform navigation. You can inject Router service and call navigate method. (Actually, routerLink directive does the same.) Remove routerLink directive, instead call your onClick method:

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

And in component class inject Router and do navigation in onClick method

constructor(private router: Router) {}

onClick(a: Agency) {
    this.agencyService.getArchive(a.id).subscribe(
      res => this.router.navigate(`/dashboard/agency/archived/${a.id}`),
      err => this.router.navigate(`/dashboard/agency/${a.id}`),
      });
  }