illumiMatii
illumiMatii

Reputation: 45

RouterLink to another component which path is created dynamically

I've created UserComponent which route is:

app-routing.module.ts

{
    path: ':username',
    component: UserComponent,
    children: [
      { path: 'work-time', component: WorktimeComponent },
      { path: 'absence', component: AbsenceComponent },
    ],
}

username is value of an input from LoginComponent.

The problem is when go to child component path for example "localhost:4200/:username/work-time" and want to move back to "localhost:4200/:username" using routerLink it just shows the main page which is separated component called HomeComponent.

What I've tried to do with routerLink is:

user.component.html

<a routerLink=":username">
    <h1>test</h1>
</a>

What I want is to create a routerLink which will route to for example "localhost:4200/peter" but I really don't know how to do it.

Upvotes: 1

Views: 1308

Answers (1)

Hamad Javed
Hamad Javed

Reputation: 104

You have to get the username from route params in the child component and bind that name with the link.

import { ActivatedRoute } from '@angular/router';
public username: string;

constructor(private activatedRoute: ActivatedRoute) {
  this.activatedRoute.queryParams.subscribe(params => {
        this.username = params['username'];
    });
}

<a [routerLink]="username"></a>

Upvotes: 2

Related Questions