2017-10-12 4 views
0

親コンポーネントには<router-outlet>という親コンポーネントがあり、親にはこれらのルートに向かうメニューがあり、メニューにはドロップダウンメニューがあります。現在、アクティブルートは常にメニューで強調表示されていますが、そのメニューオプションがサブメニューであれば、開いていなければ表示されません。ルートがその中にあれば、そのサブメニューを開いたままにしておきたい。子ルートのルータリンクを有効にします

私はこれを親の1か所で管理したいと考えています。現在のルートURLを取得し、サブメニューのルート文字列が含まれているかどうかを確認します。この方法の問題は、ルートが子ルートのために変更されるたびに現在のルートを取得するライフサイクルフックを見つけることができないことです。つまり、レンダリング中の新しい子コンポーネントを検出するライフサイクルフックです。

マイナーな要素を使用しているので、私のレンダラーはDOMに悪い方法でアクセスしていますか?

HTML:あなたは、観察ルーターのイベントをサブスクライブすることができ

<div 
         class="dropdown" 
         appDropdown 
         #DropdownOne 
        > 
         <button 
          class="top item btn btn-secondary dropdown-toggle" 
          type="button" 
          id="dropdownMenuButton" 
          data-toggle="dropdown" 
          aria-haspopup="true" 
          aria-expanded="false" 
         > 
          all options 
         </button> 
         <div 
          class="item dropdown-menu" 
          aria-labelledby="dropdownMenuButton" 
         > 
          <a 
           class="dropdown-item" 
           routerLink="/myMenu/options/option1" 
           routerLinkActive="active" 
          > 
          option 1</a> 
          <a 
           class="dropdown-item" 
           routerLink="/myoptions/options/option2" 
           routerLinkActive="active" 
          > 
          Option 2</a> 
          <a 
           class="dropdown-item" 
           routerLink="/myoptions/options/option3" 
           routerLinkActive="active" 
          > 
          Option 3</a> 
         </div> 
    </div> 
... 
<div class="content-box col"> 
      <router-outlet></router-outlet> 
</div> 
... 

TS

export class NetworkComponent implements AfterViewInit { 
    @ViewChild('DropdownOne') dropdownOne: ElementRef; 
    @ViewChild('DropdownTwo') dropdownTwo: ElementRef; 
    url: string; 
    // stateOne = 'closed'; 
    // stateTwo = 'closed'; 

    constructor(private router: Router, 
       private renderer: Renderer2) {} 

    ngAfterViewInit() { 
     this.url = this.router.url; 
     console.log(this.url) 
     if (this.url.includes('interface')) { 
      console.log('TRUE') 
      this.renderer.addClass(this.dropdownOne.nativeElement, 'show') 
     } 
     if (this.url.includes('firewall')) { 
      console.log('TRUE') 
      this.renderer.addClass(this.dropdownTwo.nativeElement, 'show') 
     } 
    } 

答えて

0

。あなたがここにルータの詳細を読むことができます

constructor(private router: Router, private renderer: Renderer2) { 
    this.router.events.subscribe(() => { 
     const url = this.router.url; 
     // do your route check here 
    }); 
} 

https://angular.io/api/router/Router#events

をごサイドノートのレンダラーを使用して、私は

<div appDropdown class="dropdown" [class.show]="isDropdownOneOpen"> ... </div> 
、あなたがそうのような単純なブールを使用して同じ効果を得ることができると思います

ルートが一致したときにtrueに設定するだけです。

+0

hmmmこれは動作しません。それはコンストラクタをクリックするたびに数回呼び出し、ページが読み込まれると閉じます – FussinHussin

関連する問題