Render ข้อมูลจาก Array ด้วย ngFor
หัวข้อที่แล้วเป็นการเอาข้อมูลจากตัวแปรตัวเดียวมาแสดงผล แต่ถ้าต้องการให้แสดงข้อมูลเป็น list หรือ table ด้วยข้อมูลจากตัวแปรแบบ Array ก็สามารถทำได้เช่นเดียวกัน
ยกตัวอย่างเช่น กำหนดให้มีข้อมูลรายชื่อเพื่อนอยู่ 3 คน ดังนี้
Jack, Queen, King
ต้องการให้แสดงผลดังนี้
Friend list
- Jack
- Queen
- King
เริ่มจากสร้าง component ใหม่
>\ng generate component friend-list
ในไฟล์ src/app/app.component.html ลบโค้ดออกทั้งหมด แล้วใส่
<friend-list></friend-list>
เข้าไปแทน
ทดลองรันดู ต้องได้ผลดังรูป
ในไฟล์ src/app/friend-list/friend-list.component.ts เพิ่มข้อมูลที่ต้องการเข้าไป
import { Component, OnInit } from '@angular/core';
@Component({
selector: 'app-friend-list',
templateUrl: './friend-list.component.html',
styleUrls: ['./friend-list.component.css']
})
export class FriendListComponent implements OnInit {
friends = [
'Jack',
'Queen',
'King'
]
constructor() { }
ngOnInit() {
}
}
ในไฟล์ src/app/friend-list/friend-list.component.html เพิ่ม code ดังต่อไปนี้
<h1>Friend list</h1>
<ul>
<li *ngFor="let friend of friends"> {{ friend }}</li>
</ul>
เป็นการสั่งให้ Angular เอาข้อมูลที่อยู่ในตัวแปร friends มาแสดงผลเป็น list ตามข้อมูลที่อยู่ภายใน Array
ซึ่งจะได้ผลลัพธ์ตามรูป
จะได้ใช้บ่อยมากในการแสดงผลข้อมูลเป็นรายการ หรือเป็นตาราง