###### tags: `Angular` # 🥔了解 Directive 讓功能更多元 在前面的 [🥔從認識 Component 開始](https://hackmd.io/@Alle/HkRO2OkFc) 有說到 Component 由 Directive 擴充而來的,那在 Angular 中 [Directive](https://angular.io/guide/built-in-directives) 分成三種類型,主要的功能是擴充原有的 DOM 功能。 * Components: 擁有 Tamplate 的 Directive * [Attribute directives](https://angular.io/guide/attribute-directives): 改變某個 DOM 元素,來影響顯示方式或一些行為 (NgClass, NgStyle, NgModel) * [Structural directives](https://angular.io/guide/structural-directives#creating-a-structural-directive): 透過新增/移除 DOM 元素來改變 DOM 的佈局 (NgIf, NgFor, NgSwitch)。 [DOM](https://developer.mozilla.org/zh-TW/docs/Web/API/Document_Object_Model) ## Directive 範例 [Naavjopgege.Angular ](https://stackblitz.com/angular/naavjopgege?file=src%2Fapp%2Fapp.component.html) ```typescript= @Directive({ selector: '[appHighlight]' }) export class HighlightDirective { constructor(private el: ElementRef) { } @HostListener('mouseenter') onMouseEnter() { this.highlight('yellow'); } @HostListener('mouseleave') onMouseLeave() { this.highlight(''); } private highlight(color: string) { this.el.nativeElement.style.backgroundColor = color; } } ``` ```htmlembedded= <p appHighlight>Highlight me!</p> ``` ## Directive 使用時機 Directive 本身很適合拿來處理「畫面的動態需求」。 [drag&drop](https://stackblitz.com/edit/angular-ivy-uhlcec?file=src/app/drag/drag.directive.ts) 儘管他適合拿來處理動態畫面,我們實際上還是不常會使用到他,主要的原因有兩種: 1. 不夠複雜的「畫面的動態需求」,並不值得使用 Directive 來實現。 2. 時間不夠,容易直接使用套件取代。
×
Sign in
Email
Password
Forgot password
or
By clicking below, you agree to our
terms of service
.
Sign in via Facebook
Sign in via Twitter
Sign in via GitHub
Sign in via Dropbox
Sign in with Wallet
Wallet (
)
Connect another wallet
New to HackMD?
Sign up