美文网首页
angular 6 from rookie to master

angular 6 from rookie to master

作者: ElliotG | 来源:发表于2018-11-16 15:55 被阅读0次

    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>
    

    相关文章

      网友评论

          本文标题:angular 6 from rookie to master

          本文链接:https://www.haomeiwen.com/subject/itdmfqtx.html