|
來處理資料。date
:格式化日期uppercase
/ lowercase
:大小寫轉換currency
:數字轉貨幣slice
:取部分字串或陣列範例:
<p>今天是 {{ today | date:'yyyy/MM/dd' }}</p>
<p>金額:{{ 1999.5 | currency:'TWD' }}</p>
ngIf
、ngFor
)。[ngClass]
、[ngStyle]
)。範例:
<p [ngClass]="{ 'highlight': isActive }">Hello</p>
在 projects.component.html
加上內建 Pipe:
<article class="card" *ngFor="let project of projects; trackBy: trackByTitle">
<h3>{{ project.title | uppercase }}</h3>
<p class="muted">{{ project.tech | slice:0:20 }}...</p>
<p>{{ project.desc }}</p>
</article>
👉 專案標題會全大寫,技術描述只取前 20 個字。
建立一個 Pipe:
ng g pipe pipes/summary
summary.pipe.ts
import { Pipe, PipeTransform } from '@angular/core';
@Pipe({ name: 'summary' })
export class SummaryPipe implements PipeTransform {
transform(value: string, limit = 30): string {
if (!value) return '';
return value.length > limit ? value.substring(0, limit) + '...' : value;
}
}
使用範例:
<p>{{ project.desc | summary:40 }}</p>
👉 描述超過 40 個字會自動加上 ...
。
在 skills.component.html
增加 [ngClass]
,當技能是前端類別就高亮:
<li *ngFor="let s of view; trackBy: trackByName"
[ngClass]="{ 'highlight': s.category === 'frontend' }">
{{ s.name }}
</li>
skills.component.scss
.highlight {
background: #e0f2fe;
border: 1px solid #38bdf8;
}
建立 Directive:
ng g directive directives/hoverHighlight
hover-highlight.directive.ts
import { Directive, ElementRef, HostListener, Renderer2 } from '@angular/core';
@Directive({
selector: '[appHoverHighlight]'
})
export class HoverHighlightDirective {
constructor(private el: ElementRef, private renderer: Renderer2) {}
@HostListener('mouseenter') onEnter() {
this.renderer.setStyle(this.el.nativeElement, 'background', '#fef9c3');
}
@HostListener('mouseleave') onLeave() {
this.renderer.removeStyle(this.el.nativeElement, 'background');
}
}
使用範例(在 Skills 清單套用):
<li *ngFor="let s of view; trackBy: trackByName" appHoverHighlight>
{{ s.name }}
</li>
👉 滑鼠移入技能項目會自動變色。
appXxx
el.nativeElement.style
renderer.setStyle
→ 更安全,更適合 SSR明天我們進入 HttpClient 串接 API 與 RxJS:
HttpClient
呼叫 APIasync
pipe