angularjsangular5routerlinkrouterlinkactive

How to pass variable query parameters with a routerLink in Angular 5


Within an *ngFor loop, where I'm building a list of search results (mat cards) with sample reading texts, I want to allow the user to click on one of them to read more, and open a route to a document template populated with the right doc.

This static HTML works with routerlinkactive catching the params in the docview page...

<button mat-button [routerLink]="['/docview', {sDocName: 'AW010001'}]">READ MORE...</button>

I want to replace the hardcoded Doc ID 'AW010001' with the appropriate ID for each iteration through the *ngFor. But this code fails...

<button mat-button [routerLink]="['/docview', {sDocName: '{{sDocIDs[i]}}'}]">READ MORE...</button>

The error I get is the typical...

Parser Error: Got interpolation ({{}}) where expression was expected at column 25 in [['/docview', {[sDocName]:'{{sDocIDs[i]}}' }]]


Solution

  • Actually... I ended up moving the routerLink functionality into a function in my .ts file for that component...

      readMore(sDoc: string) {
        this.router.navigate(['/docview', {sDocName: sDoc}]);
        window.scrollTo(0, 0);
      }
    

    Then in my HTML, I use a variable that is associated with all the other story metadata... in this case I used an array for development, but will eventually replace that array variable with an element of a data model for the stories.

    <button mat-raised-button (click)="readMore(DocIDs[i])">READ MORE...</button>
    

    This is working well for me.