开发简化版NgFor

开发简化版NgFor

下面是自定义实现一个简化版本的NgFor指令,一般来说使用Angular默认的即可,但是在追求高性能的时候,或许你需要这样一个简化版本的指令,让你的程序运行流畅、纵享丝滑。

直接贴出代码。

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

export class SimpleNgForRow {
  constructor(public $implicit: any, public index: number) {}

  get even(): boolean { return this.index % 2 === 0; }

  get odd(): boolean { return !this.even; }
}

@Directive({selector: '[simpleNgFor][simpleNgForOf]'})
export class SimpleNgFor implements DoCheck {
  @Input() simpleNgForOf: any[]; // 开放属性,用于绑定数据

  constructor(
      private _viewContainer: ViewContainerRef, private _template: TemplateRef<SimpleNgForRow>) {}

  @Input()
  set ngForTemplate(value: TemplateRef<SimpleNgForRow>) {
    if (value) {
      this._template = value;
    }
  }

  ngDoCheck() {
    const oldLen = this._viewContainer.length;
    const newLen = this.simpleNgForOf.length;

猜你喜欢

转载自blog.csdn.net/wf19930209/article/details/104548161