Devdit
 

Angular สร้าง Template header footer

195

บทความนี้สอนวิธีสร้าง template ประกอบด้วยส่วน header footer body ด้วย Angular คือเมื่อเราเข้าแต่ละเมนูเนื้อหาตรงกลางจะเปลี่ยนตามเมนูที่เลือก แต่ส่วน header และ footer หรือ menu จะเหมือนกัน หลักการคือสร้าง routes ที่มี path หลักเป็น component template และ children path เป็นแต่ละ component ที่ต้องการใช้ template ดังกล่าว มีรายละเอียดดังนี้

 

สมมติมี 2 เมนู คือ product และ about โดยมีส่วน header, menu และ footer ที่เหมือนกันเรียกส่วนดังกล่าวว่า Template

 

ตัวอย่าง Angular สร้าง header footer template

1. สร้าง component product และ about ด้วยคำสั่ง

ng g c product
ng g c about

ทั้ง 2 component คือ 2 หน้าของ Angular ที่จะใช้ template เดียวกัน

 

2. สร้าง component ชื่อ template สำหรับเป็น template หลักของเว็บไซต์

ng g c template

 

3. แก้ไขไฟล์ app-routing.module.ts ใน src/app/ โดยการ import ทั้ง 3 component และเพิ่มเส้นทางใน routes

...
import { AboutComponent } from './about/about.component';
import { TemplateComponent } from './template/template.component';
import { ProductComponent } from './product/product.component';

const routes: Routes = [
  {
    path: '',
    component: TemplateComponent,
    children: [
      {
        path: 'about',
        component: AboutComponent
      },
      {
        path: 'product',
        component: ProductComponent
      }      
    ]
  }
];
...

จากโค้ดโหลด TemplateComponent ด้วย path: ‘’ (ค่าเริ่มต้น) และกำหนดให้ 2 หน้าใช้ template เดียวกันคือ about และ product โดยกำหนดทั้งคู่ไว้ใน children ของ TemplateComponent

 

4. เขียนโค้ดในไฟล์ template.component.html ที่อยู่ใน src/app/template/ ดังนี้

<div>header</div>
<div><a routerLink="product">product</a> | <a routerLink="about">about</a></div>
<router-outlet></router-outlet>
<div>footer</div>

จากโค้ดสร้างส่วน header, เมนูประกอบด้วยลิงก์เชื่อมโยง 2 หน้าคือ product และ about พร้อมกับใช้แท็ก router-outlet สำหรับแสดงเนื้อหาของ component ที่ถูกเลือก สุดท้ายสร้างส่วนของ footer

 

5. ทดลองรันโปรเจค Angular และกดคลิกเมนู product และ about หากสำเร็จเนื้อหาจะเปลี่ยนตามเมนูที่เลือกแต่ header, menu และ footer จะเหมือนกัน เพราะใช้ template เดียวกัน

 

สรุป การสร้าง template ใน Angular แนะนำให้กำหนด path หลักด้วย template component และกำหนด children ด้วย component หรือหน้าต่างๆ ที่ต้องการใช้ template ดังกล่าว และอย่าลืมใส่แท็ก router-outlet ในไฟล์ html ของ template component เพื่อรองรับเนื้อหาของแต่ละเมนูที่ถูกเรียกใช้งาน

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