Targeting parent's router-outlet from child component in Angular 2?

…衆ロ難τιáo~ 提交于 2019-12-12 18:29:37

问题


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



来源:https://stackoverflow.com/questions/38470032/targeting-parents-router-outlet-from-child-component-in-angular-2

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!