Neo
Neo

Reputation: 696

Get boolean indicating which route is active [Angular 2]

I have an app.component.ts component which template contains several tab components, each one containing a particular link:

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>

The HTML template of the tab component is tab.component.html:

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

I'm looking for a way to get a boolean value inside my TabComponent class, indicating which route is active.

Here is my TabComponent class:

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');
    }
}   

I would to store the information indicating if the route corresponding to the tab is active or not in the isActive boolean attribute of this typescript class.

Upvotes: 2

Views: 941

Answers (1)

Sandeep
Sandeep

Reputation: 121

You can use route param in the routerLink in the tab link so that you can catch that value in the Class with ActivatedRoute as mentioned in the Angular doc:

Upvotes: 0

Related Questions