Week 11 · Day 06 — 實作:分類與標籤

學習目標

  • 為任務加入分類與標籤
  • 建立分類管理介面
  • 在任務表單填寫分類與標籤

重點

資料延伸

export interface Category {
  id: string;
  name: string;
}

export interface Todo {
  // ...既有
  category?: string;      // 分類 id
  tags: string[];         // 標籤陣列
}

分類管理 - 建立 CategoryService(get / create / delete) - 在設定頁提供分類 CRUD

getCategories(): Observable<Category[]> {
  return this.http.get<Category[]>(`${this.api}/categories`);
}

任務表單加入分類選擇

<mat-form-field>
  <mat-label>分類</mat-label>
  <mat-select formControlName="category">
    <mat-option *ngFor="let c of categories$ | async" [value]="c.id">
      {{ c.name }}
    </mat-option>
  </mat-select>
</mat-form-field>
- 用 mat-select 下拉選分類

標籤輸入 - 用 Tag 輸入(mat-chip-list)或簡單的「輸入後按 Enter 加入陣列」

addTag(tag: string): void {
  const tags = this.form.get('tags')?.value as string[];
  this.form.get('tags')?.setValue([...tags, tag].filter(Boolean));
}

篩選(結合明日) - 分類與標籤也是篩選的重要欄位

實作

  1. 定義 Category + 延伸 Todo.tags
  2. 建立分類服務與管理頁
  3. 任務表單加入分類 mat-select 與標籤輸入
  4. 儲存時正確帶入 category / tags

作業

  • 建立分類的管理功能
  • 任務表單可選分類
  • 可為任務加上多個標籤