Quantcast
Channel: cc :: somkiat
Viewing all articles
Browse latest Browse all 2069

ลองใช้งาน Angular Signals

$
0
0

หลังจากที่ Angular 16 ถูกปล่อยออกมานั้น
มีความสามารถใหม่ที่ออกมาคือ Angular Signals
ซึ่งผมก็ไม่เคยใช้งาน
ดังนั้นมาลองทำความรู้จัก ด้วยการลองใช้งานกันดีกว่า
มาเริ่มกันเลย

ขั้นตอนแรกทำการ install/upgrade Angular 16 ก่อน

[code] $npm install -g @angular/cli $ng version Angular CLI: 16.0.2 Node: 18.14.2 Package Manager: npm 9.5.0 [/code]

ขั้นตอนที่สอง ลองสร้าง project และใช้งาน Sinals กันหน่อย

App component ใช้งาน Signals

[gist id="eb073a4ecac841ee0fd99ed892f9256b" file="app.ts"]

ทำการใช้งาน title ใน HTML ของ component

[gist id="eb073a4ecac841ee0fd99ed892f9256b" file="app.html"]

ขั้นตอนที่ 3 ทำการ update Signals ผ่าน method update()

[gist id="eb073a4ecac841ee0fd99ed892f9256b" file="app_02.ts"]

ขั้นตอนที่ 4 ทำการ mutate หรือแก้ไขข้อมูลบางส่วน โดยไม่ต้องส่งหรือ update ทั้งหมด

ยกตัวอย่างเช่นเปลี่ยนข้อมูลบาง property ของ object
จะใช้ผ่าน mutate() ดังนี้

[gist id="eb073a4ecac841ee0fd99ed892f9256b" file="app_03.ts"]

ขั้นตอนที่ 4 ทำการใช้งาน Compute() สำหรับการ update ข้อมูลของ Signals อื่น ๆ

ในกรณีที่มีการ update ค่าหนึ่ง ๆ แล้ว
ให้ทำการ update ค่าใน Signals อื่น ๆ ที่เกี่ยวข้องด้วยแบบอัตโนมัติ
โดยไม่ต้องใช้งานผ่าน update()
สามารถใช้งาน compute() ได้ดังนี้

[gist id="eb073a4ecac841ee0fd99ed892f9256b" file="app_04.ts"]

Reference Websites


Viewing all articles
Browse latest Browse all 2069

Trending Articles