Skip to content

Module and @ngModule#

目的#

  • 將巨大的應用程式拆成一個一個模塊
  • 每個模塊都包含特定功能的函式庫或元素

JS模組#

  • export: 此程式可用於其他模組
  • import: 引入其他模組到此程式
  • Angular 框架採用

Angular模組#

  • 使用 @ngModule 定義 metadata 供編譯使用

@ngModule#

  • declarations: 模組中可宣告的物件,像是Component、Directive、Pipe,是這個模組所擁有的元件
  • imports: 要使用外部模組,必須先引入到這個模組才可以使用外部模組的物件
  • providers: 加入服務提供者,會以執行階段動態注射的方式載入
  • bootstrap: 指定Angular入口元件,Angular會建立這個元件

常用模組#

Module 用途
BrowserModule 在瀏覽器執行應用程式時
CommonModule 使用ngIf、ngFor
FormsModule 使用 ngModel 及 template driven form 時
ReactiveFormsModule 使用 Reactive Form
RouterModule 使用 router 功能
HttpClientModule 與 遠端伺服器 連結時需要用到

Lifecycle#

stateDiagram-v2
    [constructor] --> [ngOnChanges]
    [ngOnChanges] --> [ngOnInit] 
    [ngOnInit] --> [ngDoCheck]
    [ngDoCheck] --> [ngAfterContentInit]
    [ngAfterContentInit] --> [ngAfterContentChecked]
    [ngAfterContentChecked] --> [ngAfterViewInit]
    [ngAfterViewInit] --> [ngAfterViewChecked]
    [ngAfterViewChecked] --> [ngOnDestroy]
ngOnChanges
  • Called after a bound input property changes
  • 當綁定的值變動時觸發,可觸發多次
ngOnInit
  • Called once the component is initialized
  • 在onChanges執行完後觸發,若onChanges沒有觸發則直接觸發,只觸發一次
ngDoCheck
  • Called during every change detection run
ngAfterContentInit
  • Called after content (ng-content) has been projected into view
  • <ng-content>被呼叫後觸發,只觸發一次
ngAfterContentChecked
  • Called every time the projected content has been checked
  • doCheck之後調用
ngAfterViewInit
  • Called after the component’s view (and child views) has been initialized
  • 各種UI被組裝完成後調用,只調用一次 EX: <input>標籤載入
ngAfterViewChecked
  • Called every time the view (and child views) have been checked
  • EX: <input [(ngModel)] = "test" > 當綁定值變更時被觸發
ngOnDestroy
  • Called once the component is about to be destroyed
  • 只觸發一次,通常會在onDestroy的地方取消訂閱,避免memory leak

語法#

@Input
  • 允許data流入子component
@Output
  • 允許子component往外傳送data
@ViewChild
  • We need @ViewChild if we want to access a template's local reference from the class of the same component (if we can't pass it as a method parameter).
  • 可以直接讓parent component直接呼叫child內提供的public 屬性和方法,不需要使用 @Input和 @Output
  • 需要在 ngAfterViewInit() 後才能使用
  • 取得有兩種方式:
    1. #id
    2. className

      .html

      <h1 #title1></h1>
      

      .ts

      @ViewChild("title1") h1: ElementRef | any;
      

@ViewChildren
  • 需要在 ngAfterViewInit() 後才能使用
    @ViewChildren(類別名稱) views: QueryList<類別名稱>
    
@ContentChild
  • 需要在 ngAfterContentInit() 後才能使用
@ContentChildren
  • 需要在 ngAfterContentInit() 後才能使用
@HostListener
  • 提供元素事件的處理方法,可以綁定任何標準的DOM事件

ng-content

ng-template
  • Tag不會顯示在HTML上,透過參考才會呈現 → 被動的
ng-container
  • DOM的容器,Tag不會顯示在HTML上,只會單純顯示內容