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<Object>) {
  }

  @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
<button *counter="let page of pageCount" (click)="changePage(page)"
        class="btn btn-outline-primary"
        [class.active]="page == selectedPage">
  {{page}}
</button>
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容