﻿# 如何在 Angular 16 加入 Bootstrap 5 網頁框架

Bootstrap 5 是一個流行的前端開發框架，用於構建具有響應式設計的網站和應用程序。Bootstrap 最初由 Twitter 團隊開發，並於 2011 年首次發布。Bootstrap 5 是 Bootstrap 框架的最新版本，於 2020 年底發布。本篇文章我將分享如何用最有效率的方式在 Angular 16 專案加入 Bootstrap 5 相關資源。

### 建立 Angular 專案與初始化 ng-bootstrap 元件

事實上，要在現有的 Angular 專案加入 Bootstrap 5 真的非常簡單，只要三個步驟：

1.  建立 Angular 16 獨立元件專案
    
    ```bash
    ng new demo1 --standalone --routing --style css --skip-tests
    ```
    
2.  進入 `demo1` 目錄
    
    ```bash
    cd demo1
    ```
    
3.  加入 `@ng-bootstrap/ng-bootstrap` 套件
    
    ```bash
    ng add @ng-bootstrap/ng-bootstrap
    ```
    
    ![image](https://stwillblogassets.blob.core.windows.net/files/images/external/stwillblogassets.blob.core.windows.net/83efed2d5c8c25249e0d-69a6fa49-72d2-43f9-a80a-ae26d631cfb4.webp)
    

別懷疑，就這三個步驟，他會幫你設定好 Bootstrap 5 所有 CSS 與 JS 相依套件！ 👍

### 手動安裝 ng-bootstrap 的步驟

其實 `ng add @ng-bootstrap/ng-bootstrap` 實際上做了好幾個初始化步驟：

1.  加入 `bootstrap`, `@popperjs/core` 與 `@ng-bootstrap/ng-bootstrap` 相依 npm 套件
    
2.  安裝 `@angular/localize` polyfill 套件
    
3.  他在 `angular.json` 加入 Bootstrap 5 的 CSS 檔
    
    ![image](https://stwillblogassets.blob.core.windows.net/files/images/external/stwillblogassets.blob.core.windows.net/c7dfeed07f15c90f8737-fedca453-929c-49f9-9fe2-badb57f40d01.webp)
    
4.  如果建立的專案**不是**「獨立元件」架構的話，他會自動在 `app.module.ts` 加入 `NgbModule` 模組，也就是預設會把 ng-bootstrap 所有支援的元件全部都匯入，真的是超級懶人包！
    
    如果專案為「獨立元件」的話，你就要在元件中各自匯入所需用到的模組，例如：`NgbPaginationModule`。
    

### 如何在獨立元件中使用 Bootstrap 5 的 Datepicker 元件

1.  先在元件的 imports 匯入 `NgbDatepickerModule` 模組
    
    ```typescript
    import { Component } from '@angular/core';
    import { CommonModule } from '@angular/common';
    import { RouterOutlet } from '@angular/router';
    import { NgbDate, NgbDatepickerModule } from '@ng-bootstrap/ng-bootstrap';
    
    @Component({
      selector: 'app-root',
      standalone: true,
      imports: [CommonModule, RouterOutlet, NgbDatepickerModule],
      templateUrl: './app.component.html',
      styleUrls: ['./app.component.css']
    })
    export class AppComponent {
      title = 'demo1';
      onDateSelect(date: NgbDate) {
        console.log(date);
      }
    }
    ```
    
2.  套用 Template
    
    ```html
    <div class="mb-3 row">
      <ngb-datepicker #d (dateSelect)="onDateSelect($event)"></ngb-datepicker>
    </div>
    ```
    

### 相關連結

-   [Angular powered Bootstrap](https://ng-bootstrap.github.io/) a.k.a. ng-bootstrap
    -   [Getting Started](https://ng-bootstrap.github.io/#/getting-started)
    -   [Components](https://ng-bootstrap.github.io/#/components/accordion/overview)
-   [Bootstrap 5 繁體中文文件](https://bootstrap5.hexschool.com/) by 六角學院
-   [Bootstrap · The most popular HTML, CSS, and JS library in the world.](https://getbootstrap.com/)
-   [Add Bootstrap 5 In Angular 11](https://www.c-sharpcorner.com/article/add-bootstrap-5-in-angular-11/)
