angular 6 from rookie to master - 5 [BookLibrary project - custom directive]

1. Creating a Custom Directive

Angular provides a good range of built-in directives(eg: ngFor), but it is a simple process to create your own directives to solve problems that are specific to your application or to support features that the built-in directives don’t have.

  • 1-1) create the directive

counter.directive.ts

import {
  Directive, ViewContainerRef, TemplateRef, Input, Attribute, SimpleChanges
} from '@angular/core';

@Directive({
  selector: '[counterOf]'
})
export class CounterDirective {
  constructor(private container: ViewContainerRef,
              private template: TemplateRef) {
  }

  @Input('counterOf')
  counter: number;

  ngOnChanges(changes: SimpleChanges) {
    this.container.clear();
    for (let i = 0; i < this.counter; i++) {
      this.container.createEmbeddedView(this.template,
        new CounterDirectiveContext(i + 1));
    }
  }
}

class CounterDirectiveContext {
  constructor(public $implicit: any) {
  }
}
 
 
  • 1-2) register the directive in feature module
...
import { CounterDirective } from "./counter.directive";


@NgModule({
    imports: [xxx, BrowserModule, FormsModule],
    declarations: [xxx, CounterDirective],
    exports: [xx]
})
export class xx { }
  • 1-3) add component property
get pageCount(): number {
    return Math.ceil(this.repository
      .getProducts(this.selectedCategory).length / this.productsPerPage);
  }
  • 1-4) use the directive in the template

你可能感兴趣的:(angular 6 from rookie to master - 5 [BookLibrary project - custom directive])