Angular Directive(指示)
Angular中的Directive 直接翻譯是指令、指示,
我個人比較喜歡指示、指引的翻譯,代表Angular看到這個特別的詞,要去做對應的事情或動作。
指令比較像在Terminal上做的輸入。
Angular中的Directive分成以下三種:
- 元件型 Component Directive
- 屬性型 Attribute Directive
- 結構型 Structure Directive
元件型指示 Component Directive
什麼是元件型指示?
指的就是元件啦!
ex: < app-root >、< app-component >
含有樣板的指示,以標籤(tag)形式呈現
屬性型 Attribute Directive
屬性、樣式
屬性型指令有以下三種:
- ngStyle
- ngClass
- ngModel
ngStyle
app.component.html 檔案內[ngStyle]="{'font-size': 26 + counter + 'px'}"
1 | <div class="container"> |
app.component.ts中設定屬性變數(click)="count()"
1 | import { Component } from '@angular/core'; |
另一種寫法
ngStyle
app.component.html 檔案內
app.component.ts中設定屬性變數
app.component.html 檔案內=>HTML
[ngStyle]="getStyle()"
1 | <div class="container"> |
(click)="count()"
1 | import { Component } from '@angular/core'; |
[style.font-size] 綁定style
[style.color]綁定style
[ngClass]綁定class
app.component.html 檔案內
1 | <div class="container"> |
css
1 | .highlight{ |
也可以改成簡短一點
1 | <p [class.highlight]="counter % 2 == 0">偶數時會有螢光背景</p> |
全部
1 | <div class="container"> |
結構型 Structure Directive:會影響到程式流的指令
- ngIf
- ngSwitch
- ngFor
ngIf
符合條件時會動態新增DOM、不符條件時動態移除(是移除而非隱藏)
若該元素被移除,若元素裡面有其他的tag或directive 也會一併被移除。
斬草除根。
app.component.html 檔案內=>HTML
1 | <p *ngIf="counter % 2 == 0">偶數時整個DOM會被移除</p> |
ngSwitch
app.component.html 檔案內=>HTML
1 | <div class="container"> |
ngFor
*ngFor="let item of list"
app.component.ts中設定屬性變數 Ts
1 | export class AppComponent { |
1 | <div class="container" *ngFor="let item of set;"> |