2017-11-30 5 views
3

내 시도가이처럼 활성화 :은 어떻게하는 라우터 링크를 기반으로 조건부 코드를 작성 할 수는

<ul class="nav nav-tabs search-selector" role="tablist"> 
    <li routerLinkActive="active" 
    [routerLinkActiveOptions]="{ exact: true }"> 
    <a routerLink="{{ myroute[0].link }}">{{ myroute[0].label }}</a> 
    </li> 
    <li routerLinkActive="active" 
    [routerLinkActiveOptions]="{ exact: true }"> 
    <a routerLink="{{ myroute[1].link }}">{{ myroute[1].label }}</a> 
    </li> 
</ul> 
<div *ngif="route0 is active">do something related to route 0</div> 
<div *ngif="route1 is active">do something related to route 1</div> 

답변

3
당신이 길을 통과하고 뭔가를 렌더링 NgIf, 유사 자신의 구조 지시어를 만들 수 있습니다

DOM 활성 경로는 다음과 같이 당신이 지시문에 전달 하나, 뭔가 일치하는 경우 :

경우-route.directive.ts을

import { Directive, Input, TemplateRef, ViewContainerRef } from '@angular/core'; 
import { Router } from '@angular/router'; 
import { Subscription } from 'rxjs/Subscription'; 

@Directive({ selector: '[ifRoute]' }) 
export class IfRouteDirective { 

    private hasView = false; 
    private subscription: Subscription; 

    constructor(
    private templateRef: TemplateRef<any>, 
    private viewContainer: ViewContainerRef, 
    private router: Router) { } 

    @Input() set ifRoute(route: string) { 
    this.performCheck(route); 

    this.subscription = this.router.events.subscribe(
     res => { 
     this.performCheck(route); 
     } 
    ) 
    } 

    performCheck(route) { 
    if (route === this.router.url && !this.hasView) { 
     this.viewContainer.createEmbeddedView(this.templateRef); 
     this.hasView = true; 
    } else if (route !== this.router.url && this.hasView) { 
     this.viewContainer.clear(); 
     this.hasView = false; 
    }; 
    } 

    ngOnDestroy() { 
    this.subscription.unsubscribe(); 
    } 
} 

당신은 당신의 템플릿에 다음과 같이 사용합니다 :

<p *ifRoute="'/login'"> 
    This will be displayed only if you are on login route. 
</p> 
+0

가 작동하지 않습니다 작동 발견했다. 브라우저에서 정확한 경로를 클릭하면 렌더링되지만 일단 다른 경로를 탐색하면 사라지지 않습니다. 그리고 다른 경로로 시작하여 그 경로를 탐색하면 전혀 렌더링되지 않습니다. https://stackblitz.com/edit/angular-dyatjo – ishandutta2007

+0

사용자가 URL을 입력 할 때 ifRoute()가로드 된 것처럼 보이고 링크를 클릭하지 않은 경우 ifRoute()가로드 된 것처럼 보입니다. – ishandutta2007

+1

@ ishandutta2007 수정 된 답변을 확인하십시오. 각 경로 변경시 상태를 확인하려면 경로 변경을 구독해야합니다. 메모리 누수를 막기 위해'ngOnDestroy' 라이프 사이클 후크를 취소하고 있습니다. 이것이 작동하는지 알려주세요. –

0

@의 스테판 - svrkota의 대답은 훌륭하지만 *ngIf="router.url=='/login'"