目標:建立一個導覽列元件來存取主頁 (Home Page) 和部落格清單 (Blog List)。
ng g c components/navBar --flat
開啟 components/nav-bar.component.ts
並新增一個 links
物件。
export class NavBarComponent {
links = [
{
url: '/home',
text: 'Home'
},
{
url: '/blog',
text: 'Blog'
}
];
}
Imports: [RouterLink, RouterLinkActive]
<nav>
<ul class="h-full flex items-center justify-around">
@for (link of links; track link.url) {
<li class="text-[1rem]">
<a [routerLink]="link.url" routerLinkActive="active" [routerLinkActiveOptions]="{ exact: true }">{{ link.text }}</a>
</li>
}
<li> </li>
</ul>
</nav>
點擊路由器連結時,將對其套用 active
類別。 routerLinkActiveOptions
選項透過確切的名稱匹配活動連結。
styles: `
.active {
color: darkgray;
font-weight: 700;
text-decoration: underline;
}
`,
import { Component } from '@angular/core';
import { RouterOutlet } from '@angular/router';
import { NavBarComponent } from './components/nav-bar.component';
@Component({
selector: 'app-root',
standalone: true,
imports: [RouterOutlet, NavBarComponent],
template: `
<blog-nav-bar class="navbar" />
<router-outlet></router-outlet>
`,
})
export class AppComponent {}
將 NavBarComponent
附加到 imports
並在範本中顯示新元件。
styles: `
:host {
display: grid;
grid-template-rows: 60px 1fr 250px;
grid-template-columns: 1fr;
grid-template-areas: "header"
"body"
"footer"
}
.navbar {
grid-area: header;
}
`,
在瀏覽器上造訪 http://localhost:5173,點擊連結即可造訪不同頁面。
Github Repo: https://github.com/railsstudent/ironman2024-analog-blog-/blob/main/src/app/components/nav-bar.component.ts