Directives
什麼是 Directives?
Directives are "enhancements" for elements (built-in ones or components)
They can change the configuration (properties, attributes), styling or behavior of elements.
Unlike Components, Directive have no template!
Directives 是 Angular 中的特殊指令,用來 「增強」 DOM 元素(內建元素或自定義元件)。
Directives 的主要功能:
可以改變元素的配置(屬性、特性)
可以修改元素的樣式(CSS)
可以改變元素的行為(事件處理等)
可以操作 DOM(添加、移除元素等)
與元件 (Components) 的差異: 不像元件,Directive 沒有自己的模板(template)!元件其實是一種帶有模板的特殊 directive。
Angular 中的三種 Directive 類型
元件 (Components):
帶有模板的特殊 directive
例如:
<app-hero-detail></app-hero-detail>
屬性指令 (Attribute Directives):
改變元素的外觀或行為
例如:
[ngStyle]
、[ngClass]
、[ngModel]
結構指令 (Structural Directives):
改變 DOM 結構(添加或移除元素)
以
*
開頭例如:
*ngIf
、*ngFor
、*ngSwitch
常用 Directives 範例
屬性指令範例
htmlCopy<!-- ngModel 雙向繫結 -->
<input [(ngModel)]="heroName">
<!-- ngStyle 動態設定多種樣式 -->
<div [ngStyle]="{'color': isActive ? 'red' : 'blue'}"></div>
<!-- ngClass 動態設定多個 CSS 類別 -->
<div [ngClass]="{'active': isActive, 'disabled': isDisabled}"></div>
Last updated