2016-05-25 6 views
2

親コンポーネントまたはappコンポーネントで、どの子ルートがアクティブであるかを調べることができます。たとえば、アクティブなルートリンクのスタイルを設定することができます。私は[routeLink]が 'router-link-active'クラスを追加しているのを見るが、私の例では私はどのルートを使用していても常にそのクラスを持っているルート '/ home'を持っている。どのルートにいるのかをアウトレットの親に見える方法はありますか?親で、どの子供のRouteSegmentが選択されているかを知っていますか?

ngOnInit() { 
    this.router.changes.subscribe(changes => { 
    console.log('location info:', this.location.platformStrategy.path()); 
    }); 
} 

RouteTreeまたは現在アクティブで取得する方法があります:ルート変更をするとき

私は@angular/commonからLocation注入し、私はこれを見てから推測フルパスを見ることができていました親からのRouteSegment?または、router-outletを確認して、どのコンポーネントがロードされているか確認してください。

constructor(
    public router: Router, 
    public routerSerializer: RouterUrlSerializer, 
    public location: Location 
) { } 

ngOnInit() { 
    this.router.changes.subscribe(changes => { 
    this.updatePath(); 
    }); 
} 

updatePath() { 
    let path = this.location.path(); 
    let urlTree = this.routerSerializer.parse(path); 
    let node = urlTree; 
    let segment: UrlSegment = urlTree.root; 
    let result = segment.segment; 
    while (urlTree.children(segment).length > 0) { 
    segment = urlTree.children(segment)[0]; 
    if (result.length > 1) result += '/'; 
    result += segment.segment; // is a string 
    } 

    this.path = result; 
} 

children()UrlSegmentを取り、UrlSegmentの配列を返します。これは私がそれをやってしまった方法です@Gunterから

答えて

2

あなたは答えた後

constructor(private router:Router, private routeSerializer:RouterUrlSerializer, private location:Location) { 
    router.changes.first().subscribe(() => { 

     console.log('router', this.router); 
     let urlTree = this.routeSerializer.parse(location.path()); 

     // to get the individual segments of the route use 
     console.log('serializer', urlTree.children(urlTree.root)[0].segment); 
     console.log('serializer', urlTree.children(urlTree.children(urlTree.root)[0])[0].segment); 
    }); 
    } 
0

のような現在のルートにアクセスすることができます。ルートsegment.segmentは空の文字列です。「/」にしたい場合はこれを行うことができます:

関連する問題