puddlejumper26 / blogs

Personal Tech Blogs
4 stars 1 forks source link

Directives in Angular #48

Open puddlejumper26 opened 4 years ago

puddlejumper26 commented 4 years ago

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 an element, attribute, class or comment. [1]

There are three directives in Angular

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

e.g.

@Directive({ selector: '[appHighlight]' }) export class HighlightDirective { constructor(el: ElementRef) { el.nativeElement.style.backgroundColor = 'yellow'; } }

-- 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.

@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; } }


### 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
-->

@Component({ selector: 'app-root', templateUrl: './app.component.html' }) export class AppComponent { color: string; <==== }


- app.module.ts
```ts
import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { FormsModule } from '@angular/forms';

import { AppComponent } from './app.component';
import { HighlightDirective } from './highlight.directive';           <====

@NgModule({
  imports:      [ BrowserModule, FormsModule ],
  declarations: [ AppComponent, HighlightDirective ],          <====
  bootstrap:    [ AppComponent ]
})
export class AppModule { }

@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 /



## Refenernces:
[1]:[ A Practical Guide to Angular Directives ](https://www.sitepoint.com/practical-guide-angular-directives/)
[2]: https://angular.io/guide/attribute-directives