danda
danda

Reputation: 583

angular router how to call child component from the parent component

I have the following route-

const routes: Routes = [
    {
        path: '',
        component: ParentComponent,
        children: [
            {
                path: ':id',
                component: ChildComponent,
            },
        ]
    }
];

in the constructor of the parent I want to navigate to some id, for example 'test'. I tried this-

constructor(private router: Router) {
    this.router.navigate(['child']);
}

and this-

constructor(private router: Router) {
    this.router.navigate(['/child']);
}

and this-

constructor(private router: Router) {
    this.router.navigate(['./child']);
}

and this-

constructor(private router: Router) {
        this.router.navigate(['../child']);
    }

my url is - http://localhost:4200/parent.

but all of this options I go to http://localhost:4200/child instead of http://localhost:4200/parent/child

Any idea why? how can I make it relative to the parent?

Upvotes: 1

Views: 2256

Answers (1)

user4676340
user4676340

Reputation:

Because navigate takes in absolute paths.

You have to explicitly tell it to be relative :

constructor(
  private router: Router,
  private route: ActivatedRoute
) {
  this.router.navigate(['child'], { relativeTo: this.route });
}

Upvotes: 5

Related Questions