Angular 實戰 ul li active

navbar.ts

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
import { Component } from '@angular/core';
import { CommonModule } from '@angular/common';
import { RouterLink } from '@angular/router';

interface navListType{
title: string,
path: string,
}
@Component({
selector: 'app-navbar', //這是元件的名稱
standalone: true,
imports: [
RouterLink,CommonModule,
],
templateUrl: './navbar.component.html',
styleUrl: './navbar.component.scss'
})
export class NavbarComponent {

navLists: navListType[] = [
{ title: 'Home' ,path:'index'},
{title:'FetchData',path:'fetch-data'}
]
//頁面名稱
pageTitle: string = 'Home';

//
isActive: boolean = false;

//點擊頁面按鈕函式
actionList(path: string) {
this.pageTitle = path;
}
}

navBar.component.html

  • *ngFor陣列渲染,ng-container 必須引入CommonModule
  • pageTitle先定義為Home
  • actionList()函式 讓pageTitle等於點擊頁面,讓li新增activeNav class
1
2
3
4
5
6
7
8
9
10
11
12
13
14
  <ng-container>
<ul class="nav">
<li
*ngFor="let item of navLists ; let index = index"
[ngClass]="pageTitle === item.title ? 'activeNav' : ''"
>
<a class="cursor-pointer"
[routerLink]="item.path"
(click)="actionList(item.title)"
>{{item.title}}</a>
</li>
</ul>
</ng-container>

  • 樣式新增activeNav
  • </ul>
    

navbar.component.scss

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
  .nav{
list-style-type: none;
display: flex;
margin-bottom: 0rem;
padding-inline-start: 0px;
background-color: #00bcd4;
color:white;
width: 100%;
max-width: 100%;
display: flex;
justify-content: center;
height: 50px;
li{
list-style-type: none;
display: flex;
margin: auto 10px;
a{
cursor: pointer;
text-decoration: none;
color:#333;

}
}
}

.activeNav{
border-bottom: 1px solid white;
}

nav li active