Targeting parent's router-outlet from child co

2019-07-09 02:06发布

问题:

Since Angular 2 Router was frequently updated, the old questions for this topic are no longer valid. I have been searching for a solution to this problem and I have yet to find one...

So, my problem is targeting parent's component router-outlet from a child component.

For example, we have an AppComponent like this one (root of our app) :

import { Component } from '@angular/core';
import { ROUTER_DIRECTIVES } from '@angular/router';
import {HeaderComponent}  from './header.component';
import {LibraryComponent}  from './library.component';

@Component({
  selector: 'my-app',
  template: `
  <header></header>
  <library></library>
  <router-outlet></router-outlet>
  `,
  directives: [ROUTER_DIRECTIVES,HeaderComponent,LibraryComponent],
  providers: []
 })
export class AppComponent {

}

And HeaderComponent looks like this :

import { Component } from '@angular/core';
import { ROUTER_DIRECTIVES } from '@angular/router';

@Component({
selector:'header',
template:'<a routerLink="test" routerLinkActive="active">go to TEST</a>',
   directives:[ROUTER_DIRECTIVES]
})
export class HeaderComponent{}

The main part in my app.routes looks like this:

const routes: RouterConfig = [
 {
  path: 'test',
  component: TestComponent
 }
];

What exactly am I doing wrong here? When I click the link to "test", a new "test" div is created (I assume this is because of the selector in TestComponent) while the router-outlet remains empty.

Another question I also have is, why do I have to import the ROUTER_DIRECTIVES and also supply it to the directives in the child component HeaderComponent, if I have already done so in the parent component?

回答1:

Can you update your router link as below.

'<a [routerLink]="['../test']" routerLinkActive="active">go to TEST</a>'

if test is root you can do a absolute navigation 'go to TEST

RouterLink accepts an array of commands as a value when used with '[]'.

you can also change route to be like 'go to TEST'

routerLink is a directive and all directives used in a component has to provide in component metadata inside directives property. ROUTER_DIRECTIVE is a constant in @angular/router package which gives you array of relevant directive and routerLink is one of them. Hence by using that you add routerLink directive in that array. You could(I am not sure if imported in router package) can pass just routerLink in that array and it will work.

For more details see official docs