首页 文章

Angular 2,为路由器链接添加活动类[最佳实践]

提问于
浏览
2

我正在使用 Input routerLinkActive将活动类添加到某个特定的URL . 但我希望如果特定链接检测到一个字块,那么该链接始终处于活动状态 . 让我解释一下:如果我定义的路由是 /rent/page/:id ,并进入我的模板,我这样做:

<a [routerLinkActive]="['active']" [routerLink]="['/rent/page/1']" title="">rent</a>

如果地址栏中的网址与定义的路线匹配,则它会起作用,并且会添加 active 类 . 我的主导航包含 rent link will be active .

但我想要更多,如果我的路由有这个定义 /rent/:property/:name/:id ,我点击网址,它不会将活动链接添加到我的主导航 .

我找到了以下解决方案:

// ...
   this._router.events.subscribe(
        (urlObj) => {
            if(urlObj.url.match(/^(\/rent).*$/)) {
                this.active["rent"] = true;
            }
        }
    )
    // ...

每当我将 rent 匹配到当前网址时,我将属性 rent 设置为对象 active 并将其添加到我的租借导航中 . 之前提到的模板,我将其改为:

<a [class.active]="active['rent']" [routerLink]="['/rent/page/1']" title="">rent</a>

它有效,但我不确定,这是不是一个好的做法 .

我的问题是: How to routerLinkActive if I want to keep specific link active, even if user changes the page? Is there an alternative way to do this using [routerLinkActive] ?

1 回答

  • 0

    这可以通过router-link这样完成:

    <router-link :to="{name :'root'}">Root</router-link>
    <router-link :to="{name :'foo'}">Go to Foo</router-link>
    <router-link to="to="/bar">Go to Bar</router-link>
    

    / bar“>去酒吧

    查看以下小提琴:http://jsfiddle.net/xgrjzsup/3276/

相关问题