首页 文章

获取布尔值,指示哪条路线处于活动状态[Angular 2]

提问于
浏览
2

我有一个app.component.ts组件,该模板包含多个选项卡组件,每个组件包含一个特定的链接:

app.component.html:

<h1>Tabs container</h1>
<div>
    <nav>
        <tab *ngFor="let tab of tabList" [name]="tab.name" [link]="tab.link" (eventEmitter)="closeTabEvent($event)"></tab>
    </nav>    
</div>
<div>
    <router-outlet></router-outlet>
</div>

选项卡组件的HTML模板是tab.component.html:

<a [routerLink]='link'  routerLinkActive="router-link-active">{{name}}</a>
<button *ngIf="tabIndex > 0" (click)="closeTab('tabToCloseKey')">Close tab</button>

我正在寻找一种方法来获取我的TabComponent类中的布尔值,指示哪个路由是活动的 .

这是我的TabComponent类:

export class TabComponent implements OnInit {
    @Input() name: string;
    @Input() link: string;
    @Input() param: string;
    targetArray: Array<any>;
    @Output() eventEmitter = new EventEmitter<[number, boolean]>();
    // @Output() isActiveEmitter = new EventEmitter<boolean>();
    static lastTabIndex: number = 0;
    tabIndex: number = 0;
    isActive: boolean = true;
    // @ViewChild('routerLinkActive') a;
    // el: HTMLElement;
    // className: string;

    constructor(private router: Router, private sharedService: SharedService, private _elRef: ElementRef) {}

    ngOnInit() {
        // this.className = this._elRef.nativeElement.find('a').className;
        // this.className = this.el.className;
        this.tabIndex = TabComponent.lastTabIndex;
        // console.log(this.className);
        TabComponent.lastTabIndex++;        
    }

    closeTab(){
        console.log('tab closed at index: ' + this.tabIndex);
        let tuple: [number, boolean];
        tuple = [this.tabIndex, this.isActive];
        this.eventEmitter.emit(tuple);
        this.hideTabComponent();
    }

    hideTabComponent(){
        console.log('Hiding component');
    }
}

我将在此typescript类的isActive boolean属性中存储指示对应于该选项卡的路由是否处于活动状态的信息 .

1 回答

  • 1

    您可以在选项卡链接中的routerLink中使用route param,以便您可以使用Angular doc:中提到的ActivatedRoute类捕获该值 .

相关问题