自定義屬性型 Directive(一):基礎知識
創建自定義的屬性型 Directive
使用 CLI 創建
最簡單的方式是使用 Angular CLI:
# 完整版
ng generate directive name
# 簡短版
ng g d name
手動創建
也可以手動創建一個新文件,基本格式如下:
import { Directive } from '@angular/core';
@Directive({
selector: 'a[appSafeLink]',
standalone: true,
})
export class SafeLinkDirective {
constructor() {
console.log('safe link directive is active!');
}
}
Directive 配置
在 @Directive
裝飾器中需要設定一些重要屬性:
selector
這決定了 Directive 在哪些 HTML 元素上生效:
標籤選擇器:
'app-safe-link'
— 匹配特定的組件標籤屬性選擇器:
'[appSafeLink]'
— 匹配具有此屬性的任何元素組合選擇器:
'a[appSafeLink]'
— 僅匹配同時是<a>
標籤且有appSafeLink
屬性的元素
standalone
在舊版 Angular 中,此設置預設為
false
或不存在在新版 Angular 中,可以設置為
true
以使用獨立模式
在組件中使用自定義 Directive
要在組件中使用自定義 Directive,需要先導入並聲明:
import { Component } from '@angular/core';
import { SafeLinkDirective } from '../safe-link.directive';
@Component({
// ...其他配置
imports: [SafeLinkDirective],
})
export class SomeComponent {}
然後在 HTML 模板中使用:
<a href="https://angular.dev" appSafeLink>Angular Documentation</a>
命名慣例
Directive class 名稱:通常以描述功能加上 "Directive" 結尾,如
SafeLinkDirective
選擇器:通常使用 camelCase 並加上自己的前綴,避免與 HTML 標準屬性衝突
Last updated