Angular 7 (Basic โคตรๆ 2)

Karoon Sillapapan
2 min readJun 5, 2019

--

Introduction to modules

Credit by : https://angular.io/guide/architecture#whats-next

An NgModule นั้นจะประกอบไปด้วย components ต่างๆ ที่มีความเกี่ยวข้องกัน และถูกนำไปใช้งานตามแต่ละ วัตถุประสงค์ โดยแต่ละ NgModule นั้นจะประกอบไปด้วย components ,service providers และ code file ต่างๆ โดยทั้งหมดจะต้องถูกกำหนดใน NgModule นอกจากนี้ NgModule นั้นสามารถ import import function หรือ Export function กับ Other NgModule อื่นๆได้

โดยในแต่ละ NgModule จะต้องมี root module 1 อันเสมอและจะใช้ชื่อว่า AppModule (app.module.ts) โดย file นี้จะทำหน้าที่ในการ start application

NgModule metadata

Credit by : https://angular.io/guide/architecture-modules#ngmodule-metadata

imports : ใช้ในการ import other module เข้ามาใช้งาน

providers : เป็นการระบุในส่วนของ service (จะมีรายละเอียดเพิ่มเติมว่า Service คืออะไรในภายหลัง…)

declarations : เป็นการระบุ components,directives,pipes ที่ใช้งานภายใน NgModule นี้

exports: เป็นการระบุชื่อสำหรับกรณีต้องการ export ให้กับ other NgModule เรียกใช้งาน

bootstrap : ใช้สำหรับระบุ Class ที่เป็น Root component

NgModules and components

ใน NgModules นั้นสามารถมีการเพิ่ม Component โดยการทำผ่าน Router หรือ Create ผ่าน Template ซึ่ง Component ทั้งหมดนั้นจะแชร์ Compilation Context รวมกัน

Compilation Context

The compilation context is basically just a fancy term for grouping of the files that TypeScript will parse and analyze to determine what is valid and what isn’t. Along with the information about which files, the compilation context contains information about which compiler options are in use. A great way to define this logical grouping (we also like to use the term project) is using a tsconfig.json file.

โดยปกติ component จะมีเพียง view เดียวซึ่งเราจะเรียกว่าเป็น Host View แต่ใน HostView นั้นสามารถมี View ของ Component อื่นๆอยู่ภายใต้ได้โดยไม่ได้จำกัดในมุมของความลึก

NgModules and JavaScript modules

NgModule นั้นต่างจากและไม่ได้เกี่ยวข้องกับ the JavaScript (ES2015) module system อะไรทั้งนั้น แต่คุณสามารถเอามาใช้เป็น Module เสริมสำหรับการทำงานของ Application ของคุณได้

โดยใน Javascript นั้นจะมองว่า 1 file นั้นก็คือ 1 module โดยถ้ามีการประกาจ Object ต่างๆขึ้นมาใน File ก็จะถือว่าอยู่ภายใต้ Module เดียวกันดังนั้น ถ้าต้องการให้ Module อื่นเรียกใช้งาน หรือจะเรียก Module อื่นๆใช้งานจึงจำเป็นต้องทำการ Import และ Export

ดังนั้นโดยส่วนตัวนั้นผมมองว่าเป็นแนวคิดที่มีความใกล้เคียงกันมาก .

Angular libraries

Angular ได้ทำการรวมรวม Javascript module ต่างๆเพื่อสำหรับนำมาใช้งานใน โดยผู้ใช้งานนั้นสามารถ Install node package manager npm

แล้วจึงสามารถทำการ Import เข้ามาใช้งานได้ โดยเราจะสังเกตุง่ายๆ ก็คือ Angular libraries นั้นจะมี prefix @angular อยู่ด้านหน้า

--

--