A directive is a function that executes whenever the Angular compiler finds it in the DOM.
Angular directives are used to extend the power of the HTML by giving it new syntax. Each directive has a name — either one from the Angular predefined like ng-repeat, or a custom one which can be called anything. And each directive determines where it can be used: in an element, attribute, class or comment. [1]
There are three directives in Angular
Components - directives with templates, components are just directives with templates - MOST COMMON directives. They use the directive API and give us a cleaner way to define them.
Structural directives - change the DOM layout by adding and removing DOM elements. - Two Examples: NgForNgIf.
structural Angular directives are much less DOM friendly, as they add or completely remove elements from the DOM. We’re actually changing the HTML structure.[1]
Attribute directives - change the Appearance or behavior of an element, component, or anohter directive. - NgStyle, can change several element styles at the same time.
We use attribute directives to apply conditional style to elements, show or hide elements or dynamically change the behavior of a component according to a changing property.[1]
A @Component requires a view whereas a @Directive does not.
A complete list of available Angular directives, we can check the official documentation - API list.
2.0 Creating an attribute directive
ng generate directive sample creates - sample.directive.ts and sample.directive.spec.ts
Directives must be declared in Angular Modules in the same manner as components.
An attribute directive minimally requires building a controller class annotated with @Directive, which specifies the selector that identifies the attribute
e.g.
app.component.html
<p appHighlight>Highlight me!</p>
highlight.directive.ts
import { Directive, ElementRef } from '@angular/core';
-- To summarize,
1) Angular found the appHighlight attribute on the host < p > element.
2) It created an instance of the HighlightDirective class
3) It injected a reference to the < p > element into the directive's constructor which sets the < p > element's background style to yellow.
### 3.0 @ HostListener
The directive could detect when the user mouse into or out of the ellement and respond by settign or clearing the highlight color.
highlight.directive.ts
```ts
import { Directive, ElementRef, HostListener } from '@angular/core'; <======
@Directive({
selector: '[appHighlight]'
})
export class HighlightDirective {
constructor(private el: ElementRef) { } <======
@HostListener('mouseenter') onMouseEnter() { <======
this.highlight('yellow');
}
@HostListener('mouseleave') onMouseLeave() { <======
this.highlight(null);
}
private highlight (color: string) {
this.el.nativeElement.style.backgroundColor = color;
}
}
The @ HostListener decorator lets you subscribe to events of the DOM element that hosts an attribute directive.
:point_right: Notice, right now the color is only hard coded
4.0 @ Input
Pass values into the directive with an @ Input data binding
:point_right: Details about @ Input please check here.
app.component.html
<p appHighlight [highlightColor]="color">Highlighted with parent component's color</p>
The [appHighlight] attribute binding both applies the highlighting directive to the
element and sets the directive's highlight color with a property binding.
app.component.ts
export class AppComponent {
color = 'yellow';
}
highlight.directive.ts
import { Directive, ElementRef, HostListener, Input } from '@angular/core';
@Directive({
selector: '[appHighlight]'
})
export class HighlightDirective {
### 5.0 Demo in Stackblitz
Demo link: https://stackblitz.com/edit/angular-directive-shawn
- app.component.html
```html
<h1>My First Attribute Directive</h1>
<h4>Pick a highlight color</h4>
<div>
<input type="radio" name="colors" (click)="color='lightgreen'">Green
<input type="radio" name="colors" (click)="color='yellow'">Yellow
<input type="radio" name="colors" (click)="color='cyan'">Cyan
</div>
<p [appHighlight]="color">Highlight me!</p>
<p [appHighlight]="color" defaultColor="violet">
Highlight me too!
</p>
<hr>
<p><i>Mouse over the following lines to see fixed highlights</i></p>
<p [appHighlight]="'yellow'">Highlighted in yellow</p>
<p appHighlight="orange">Highlighted in orange</p>
<!--
Copyright Google LLC. All Rights Reserved.
Use of this source code is governed by an MIT-style license that
can be found in the LICENSE file at http://angular.io/license
-->
/
Copyright Google LLC. All Rights Reserved.
Use of this source code is governed by an MIT-style license that
can be found in the LICENSE file at http://angular.io/license/
## Refenernces:
[1]:[ A Practical Guide to Angular Directives ](https://www.sitepoint.com/practical-guide-angular-directives/)
[2]: https://angular.io/guide/attribute-directives
Guildline
============================================
1.0 Directives overview
A directive is a function that
executes
whenever the Angular compiler finds it in the DOM.Angular directives are used to extend the power of the HTML by giving it new syntax. Each directive has a name — either one from the Angular predefined like
ng-repeat
, or a custom one which can be called anything. And each directive determines where it can be used: in anelement
,attribute
,class
orcomment
. [1]There are
three
directives in AngularComponents - directives with templates, components are just directives with templates -
MOST COMMON
directives. They use the directive API and give us a cleaner way to define them.Structural directives - change the DOM layout by adding and removing DOM elements. - Two Examples:
NgFor
NgIf
. structural Angular directives are much less DOM friendly, as theyadd or completely remove
elements from the DOM. We’re actually changing the HTML structure.[1]Attribute directives - change the
Appearance
or behavior of an element, component, or anohter directive. -NgStyle
, can change several element styles at the same time. We use attribute directives to apply conditional style to elements, show or hide elements or dynamically change the behavior of a component according to a changing property.[1]A @Component requires a view whereas a @Directive does not.
A complete list of
available Angular directives
, we can check the official documentation - API list.2.0 Creating an attribute directive
ng generate directive sample
creates -sample.directive.ts
andsample.directive.spec.ts
Angular Modules
in the same manner as components.e.g.
@Directive({ selector: '[appHighlight]' }) export class HighlightDirective { constructor(el: ElementRef) { el.nativeElement.style.backgroundColor = 'yellow'; } }
The @ HostListener decorator lets you subscribe to events of the DOM element that hosts an attribute directive.
:point_right: Notice, right now the color is only
hard coded
4.0 @ Input
Pass values into the directive with an @ Input data binding
:point_right: Details about
@ Input
please check here.app.component.html
The [appHighlight] attribute binding both applies the highlighting directive to the
element and sets the directive's highlight color with a property binding.
app.component.ts
highlight.directive.ts
@Directive({ selector: '[appHighlight]' }) export class HighlightDirective {
constructor(private el: ElementRef) { }
@Input('appHighlight') highlightColor: string; <====
@HostListener('mouseenter') onMouseEnter() { this.highlight(this.highlightColor || 'red'); }
@HostListener('mouseleave') onMouseLeave() { this.highlight(null); }
private highlight(color: string) { this.el.nativeElement.style.backgroundColor = color; } }
@Component({ selector: 'app-root', templateUrl: './app.component.html' }) export class AppComponent { color: string; <==== }
@Directive({ selector: '[appHighlight]' <==== }) export class HighlightDirective {
constructor(private el: ElementRef) { }
@Input() defaultColor: string; <====
@Input('appHighlight') highlightColor: string; <====
@HostListener('mouseenter') onMouseEnter() { <==== this.highlight(this.highlightColor || this.defaultColor || 'red'); }
@HostListener('mouseleave') onMouseLeave() { <==== this.highlight(null); }
private highlight(color: string) { this.el.nativeElement.style.backgroundColor = color; } }
/ Copyright Google LLC. All Rights Reserved. Use of this source code is governed by an MIT-style license that can be found in the LICENSE file at http://angular.io/license /