0

I made a blog using angular in which I have a root component and it has a navigation bar with router links to create a single page application. what I want to do is, when the child component is loaded I want to darken the background around the link. I coded the logic such that the link is being highlighted when we press the link, but when we reload the page the highlight is not being highlighted. I want a code logic that can work even if the page is reloaded

here is my code

app.component.ts:

import { Component } from '@angular/core';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.scss']
})

export class AppComponent {
  public bool : boolean[] = [false,false,false];

  public navItems : string[] =[
    'home',
    'about',
    'contact'
  ];

  btnClick(i:any){
    this.bool = [false, false,false];
    this.bool[i] = true;
  }
}

app.component.html

<div>
  <nav>
    <label for="header">TestApp</label>
    <ul>
      <li *ngFor="let item of navItems; let i=index" routerLink="{{item}}"
       [class.active]="bool[i]" (click)=btnClick(i)>
        {{ item }}
      </li>
    </ul>
  </nav>
</div>

app.component.scss

$nav: #027bdd;

:host {
  font-family: 'Montserrat', sans-serif;
  /* font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, Helvetica, Arial, sans-serif, "Apple Color Emoji", "Segoe UI Emoji", "Segoe UI Symbol"; */
  font-size: 14px;
  color: #333;
  box-sizing: border-box;
  -webkit-font-smoothing: antialiased;
  -moz-osx-font-smoothing: grayscale;
}
body{
  margin: 0;
}

app-root{
  margin: 0;
}
h1{
  text-align: center;
}
nav{
  font-size: 18px;
  position: relative;
  width: 100vw;
  height: 60px;
  color: white;
  margin: 0;
  display: flex;
  align-items:center;
  justify-content: space-between;
  background: $nav;
  z-index: 123;
  label{
    font-weight: 900;
    margin-left: 20px;

  }
  ul{
    margin: 0;
    padding: 0;
    display: inline-flex;
    justify-content: space-around;
    width: 35vw;
    li{
      position: relative;
      width: 140px;
      height: 60px;
      align-items: center;
      display: inline-flex;
      list-style: none;
      justify-content: center;
      text-transform: capitalize;
      outline: none;
      cursor: pointer;
    }
  }
}
.active{
  transition: background 0.2s ease-in-out;
  cursor: pointer;
  background: darken($nav, 10%);
}
Meher Chaitanya
  • 123
  • 1
  • 3
  • 8

1 Answers1

0

What you are looking for is routerLinkActive (https://angular.io/api/router/RouterLinkActive). It is builtin in Angular. The directive sets a css class based on the currently active route.

You can read more about it here: https://angular.io/guide/router#router-links

Otherweise there is a similar question, answering your problem. See In Angular, how do you determine the active route?

FredericBirke
  • 1,002
  • 1
  • 7
  • 13