เริ่มต้น hello world ใน Angular มีดังนี้
- ติดตั้ง Angular CLI
1 | npm install -g @angular/cli |
- สร้าง project Angular
1 | ng new hello-world |
- เปิด project Angular ใน Visual Studio Code
1 | cd hello-world |
- เพิ่มข้อความ “Hello World” ลงในหน้า HTML
1 | <h1>Hello World!</h1> |
- รัน project Angular
1 | ng serve |
เบราว์เซอร์จะเปิดหน้าเว็บที่มีข้อความ “Hello World!” แสดงอยู่
ตัวอย่างโค้ด hello world ใน Angular
1 | import { Component, OnInit } from '@angular/core'; |
1 | <h1>Hello World!</h1> |
การอธิบายโค้ด
@Component()decorator กำหนดว่าคลาสAppComponentเป็นคอมโพเนนต์ Angularselectorproperty กำหนดค่า selector ของคอมโพเนนต์templateUrlproperty กำหนด URL ของไฟล์ template ที่ใช้แสดงหน้าเว็บstyleUrlsproperty กำหนด URL ของไฟล์ CSS ที่ใช้กำหนดสไตล์ให้กับหน้าเว็บconstructor()ฟังก์ชันตัวสร้างของคอมโพเนนต์ngOnInit()ฟังก์ชันที่ทำงานเมื่อคอมโพเนนต์ถูกโหลด
การทดสอบ hello world
เปิดเบราว์เซอร์ไปที่ http://localhost:4200/
เบราว์เซอร์จะแสดงหน้าเว็บที่มีข้อความ “Hello World!” แสดงอยู่
เพิ่มเติม
หากต้องการปรับแต่งหน้า hello world สามารถแก้ไขไฟล์ app.component.html และ app.component.css ได้
ไฟล์ app.component.html ใช้กำหนดเนื้อหาของหน้าเว็บ
ไฟล์ app.component.css ใช้กำหนดสไตล์ให้กับหน้าเว็บ