Hau Le
Hau Le

Reputation: 25

How you pass variable inside [routerlink]

I need to pass current userId to routerlink in borrow_list component

The way i declare userId in borrow_list component

userId: number;
constructor(private authService: AuthService, private bookService: BookService,
     private route: ActivatedRoute, private alertify: AlertifyService) { }



ngOnInit() {
    this.userId = this.authService.decodedToken.nameid;
    this.route.data.subscribe(data => {
      this.books = data['books'].result;
      this.pagination = data['books'].pagination;
    });
    this.borrowParam = 'loan';
    console.log(this.userId); // this one return 26
  }

Then i tried to pass userId to another component using routerlink

<div class="row">
  <div *ngFor="let b of books" class="col-sm-6 col-md-4 col-lg-4 col-xl-2">
    <app-book-card [book]="b"></app-book-card>
    <button class="btn btn-primary" [routerLink]=" 
     ['/browse/book/',this.userId,'/content/', b.id]" style="width: 75px">Read 
    </button>
  </div>
</div>

But it seem not working, no error but it direct me back to Home page

When i try to hard code the link and it work as intended i.e

[routerLink]="['/browse/book/26/content/', b.id]"

My routes.ts

{path: 'browse/book/:id/content/:bookId', component: Book_contentComponent, resolve: {book: BookContentResolver}}

I think i did it wrong somewhere?

Upvotes: 0

Views: 1739

Answers (2)

pajtim
pajtim

Reputation: 567

please try this:

<button class="btn btn-primary" [routerLink]=" ['browse', 'book', userId, 'content', 
b.id]" style="width: 75px">Read </button>

Every path segment is an element in the array.

Upvotes: 2

Qortex
Qortex

Reputation: 7456

When in template, variables are automatically taken from the underlying component. So you don't need to put this to access member variables.

In your code, you just need userId instead of this.userId, giving:

<button class="btn btn-primary" [routerLink]=" 
 ['/browse/book/', userId,'/content/', b.id]" style="width: 75px">Read 
</button>

Note: not a good practice to put style inline in your HTML.

Upvotes: 0

Related Questions