網站搜尋

javascript - 在元件類別中存取 [routerLinkActive] 的值


我有一個標籤頁元件 TabComponent,它有以下的 HTML 模板:

<a [routerLink]='link' [routerLinkActive]="[is-active]">link label</a>
<button>Close tab</button>

我想要存取 [routerLinkActive] 屬性的值,基本上我想在元件類別中取得一個變數來表示這個 routerLink 是否處於活躍狀態。我如何從元件類別內部存取它?

編輯:我認為如果我能獲取 <a> 連結標籤的 CSS 類別,那麼工作就完成了,有沒有辦法可以存取它?

答案#1

我不知道這是否有幫助,但你可以這樣在你的範本中取得值:

<a *ngFor="let child of directory; let i = index;"
   routerLink="{{child.route}}"
   routerLinkActive #rla="routerLinkActive">

   <h3>{{rla.isActive}}</h3><!--Displays boolean indicating whether or not you are navigated to this link-->
</a>

現在,你的 h3 中將顯示一個布林值,指示你當前是否已導航到該連結。

雖然這可以作為模板變數使用,但我無法將該值傳遞給 component.ts 或傳遞給其他模板指令,例如

 <a *ngFor="let child of directory; let i = index;"
   routerLink="{{child.route}}"
   routerLinkActive #rla="routerLinkActive"

   [active]="rla.isActive" <!--This doesn't insert the boolean here for some reason-->
   >    
   <h3>{{rla.isActive}}</h3>
</a>

我希望這有幫助。如果你有更接近好解決方案的進展,請更新。

答案#2

為了獲取元件中 isActive 的狀態,你需要等待 AfterContentChecked 生命周期回調。

<a routerLink="/user/bob" routerLinkActive #rla="routerLinkActive">
  Bob {{ rla.isActive ? '(already open)' : ''}}
</a>
@ViewChild('rla') private rla: RouterLinkActive;

ngAfterContentChecked(): void {
    if (this.rla?.isActive) {
        console.log('isActive')
    }
}