Alex Skotner
Alex Skotner

Reputation: 602

Angular reference id in ngClass best practices

I made this code to change the css of the nav-bar options when the active page changes.

html:

   <ul>
        <li routerLink="/" id="homePage" (click)="selected($event)"
            [ngClass]="{'default': activePage=='homePage', 'active': activePage!=='homePage' }">Home
        </li>

        <li id="placeholder" routerLink="/placeholder" (click)="selected($event)"
            [ngClass]="{'default': activePage=='placeholder', 'active':  activePage!=='placeholder' }">PlaceHolder
        </li>
    </ul>

TS:

  public selected($event) {
    var target = event.target || event.srcElement || event.currentTarget;
    this.activePage = target["id"];
  }

but I have two problems I can't figure out:

  1. I would like to be able to write the [ngClass] to check the id attribute and not just the id as a hardcoded string

  2. If I change the address manually, this code will fail and display the homepage as the active page since it the default - how do I fix this?

Upvotes: 0

Views: 296

Answers (1)

Vitalii Ilchenko
Vitalii Ilchenko

Reputation: 598

Router will help you to achieve expected behavior.

<ul>
  <li [routerLink]="routes.home"
      [ngClass]="{ 'activated': currentTab === routes.home}">
    Home
  </li>
  <li [routerLink]="routes.placeholder"
      [ngClass]="{ 'activated': currentTab === routes.placeholder}">
    PlaceHolder
  </li>
</ul>
<router-outlet></router-outlet>
import { Component } from '@angular/core';
import { Router, NavigationEnd } from '@angular/router';
import { filter, map } from 'rxjs/operators';

@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: [ './app.component.css' ]
})
export class AppComponent {

  currentTab = '';

  readonly routes = {
    home: '/home',
    placeholder: '/placeholder'
  };

  constructor(private router: Router) {
    this.router.events
      .pipe(
        filter(e => e instanceof NavigationEnd),
        map((e: NavigationEnd) => e.url)
      )
      .subscribe(newUrl => {
        this.currentTab = newUrl;
    });
  }
}

You can check how it works here

Upvotes: 1

Related Questions