Devdit
 

วิธีติดตั้ง Bootstrap ใน Angular

344

บทความนี้สอนวิธีติดตั้ง Bootstrap ใน Angular ขั้นตอนคือติดตั้ง Boostrap Framework ด้วย npm ใน Angular Project จากนั้นแก้ไขไฟล์ angular.json โดยการเพิ่มโค้ดในส่วนของ styles และ scripts เพื่อเรียกใช้ Bootstrap ใน Angular Framework มีขั้นตอนดังนี้

 

ตัวอย่าง วิธีติดตั้ง Bootstrap ใน Angular

1. เปิด command line เข้าไปใน Angular Project และรันคำสั่งเพื่อติดตั้ง package bootstrap เวอร์ชันล่าสุด

npm install --save bootstrap@latest

 

2. เปิดไฟล์ angular.json อยู่ที่ root ของ Angular Project และเพิ่มโค้ดเพื่อเรียกใช้ CSS และ JS ดังนี้

2.1 เรียกใช้ CSS เพิ่มโค้ดลงใน "styles" ของเดิม

"styles": [
  "src/styles.less"
],

เป็น

"styles": [
  "node_modules/bootstrap/dist/css/bootstrap.min.css",
  "src/styles.less"
],

2.2 เรียกใช้ JS เพิ่มโค้ดลงใน "scripts" ของเดิม

"scripts": [],

เป็น

"scripts": [
  "node_modules/bootstrap/dist/js/bootstrap.bundle.min.js"
],

 

3. เพิ่มโค้ดไว้ด้านล่างสุดในไฟล์ src/app/app.component.html เพื่อทดสอบการติดตั้ง Bootstrap ใน Angular ด้วย Component Modal

<button type="button" class="btn btn-primary" data-bs-toggle="modal" data-bs-target="#exampleModal">
  Launch demo modal
</button>

<div class="modal fade" id="exampleModal" tabindex="-1" aria-labelledby="exampleModalLabel" aria-hidden="true">
  <div class="modal-dialog">
    <div class="modal-content">
      <div class="modal-header">
        <h1 class="modal-title fs-5" id="exampleModalLabel">Modal title</h1>
        <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
      </div>
      <div class="modal-body">
        ...
      </div>
      <div class="modal-footer">
        <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Close</button>
        <button type="button" class="btn btn-primary">Save changes</button>
      </div>
    </div>
  </div>
</div>

 

4. ทดลองรัน http://localhost:4200/ หรือ URL อื่นๆ หากสำเร็จเมื่อกดปุ่มจะแสดง Modal แบบ Popup ขึ้นมา เป็นอันเสร็จสิ้นการติดตั้ง Boostrap Framework ทั้งในส่วนของ CSS และ JS ใน Angular Project ของเรา

 

สรุป ขั้นตอนการติดตั้ง Bootstrap ใน Angular แบ่งเป็น 3 ขั้นตอนคือ

1. ติดตั้ง Boostrap ด้วย npm ลงใน Angular Project

2. เพิ่มการเรียกใช้ CSS และ JS ของ Boostrap ลงในไฟล์ angular.json

3. ทดลองเขียนโค้ดเรียกใช้ Component ของ Boostrap ในตัวอย่างคือ Modal เพราะใช้ทั้ง CSS และ JS

แก้ไข 5 เดือนที่แล้ว
ชอบ
ลิ้งก์
แชร์
Devdit มีช่อง YouTube แล้ว
เราสร้างวิดีโอเกี่ยวกับเทคโนโลยี ทำตามง่ายๆ