2017-10-12 134 views
0

我有一個父組件,其中包含一個<router-outlet>,父母有一個指向這些路由的菜單,菜單的子菜單是下拉菜單。目前,活動路線始終在菜單中突出顯示,但如果該菜單選項是子菜單,則不會顯示,除非您打開它。如果路線在其中,我想保留該子菜單。保持路由器鏈接對子路由有效

我想在一個地方,父母管理這個。我當前的嘗試獲取當前的路由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

嗯,這是行不通的。它每次點擊多次調用構造函數,並在頁面加載時關閉它 – FussinHussin