Angular 6 Class Binding

Angular 6 Class Binding

It would be nice to indicate which page a user is currently on in the left sidebar, perhaps by adding a class to the icon that will make its' background blue? Sure!
Visit the /src/app/sidebar/sidebar.component.ts file and add the following:
import { Component, OnInit } from '@angular/core';
import { Router, NavigationEnd } from '@angular/router';

export class SidebarComponent implements OnInit {

  currentUrl: string;

  constructor(private router: Router) {
    router.events.subscribe((_: NavigationEnd) => this.currentUrl = _.url);
  }

  ngOnInit() {}

}
We're importing the Router and NavigationEnd, then defining a string property currentUrl. Then, we create an instance of the Router in order to subscribe to router.events. It will provide us with a string, which is the current router path.
Open the sidebar.component.html file and update it to match:
<nav>
  <ul>
    <li>
      <a routerLink="" [class.activated]="currentUrl == '/'">
        <i class="material-icons">supervised_user_circle</i>
      </a>
    </li>
    <li>
      <a routerLink="posts" [class.activated]="currentUrl == '/posts'">
        <i class="material-icons">message</i>
      </a>
    </li>
  </ul>
</nav>
Class binding works by binding [class.csspropertyname] to a template expression. It will only add the .activated CSS ruleset (defined in styles.scss) if our currentUrl is equal to either / or /posts.

Save it. The result should now look like this:
Angular 6 Class Binding Angular 6 Class Binding Reviewed by Pakainfo on August 08, 2018 Rating: 5

No comments:

'Heartbroken' family of Nigerian man who died at Calgary airport wants answers

'Heartbroken' family of Nigerian man who died at Calgary airport wants answers Bolante Idowu Alo died following altercation wit...

Powered by Blogger.