2017-10-12 136 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