无法在手动单元格中编译角度分量

时间:2017-07-04 14:48:57

标签: angular handsontable

真的遇到了问题,我正在使用带有angular2的双手。在动手中,我使用单元格渲染来填充单元格,并且该单元格包含一个角度组件。

但问题是单元格没有在角度范围内编译

1 个答案:

答案 0 :(得分:0)

您需要编译要在单元格中显示的组件,并将组件的html添加到自定义渲染器中的单元格。这是一个例子:

import { Component, ComponentFactory, ComponentFactoryResolver, ComponentRef,
  OnInit, OnDestroy, ViewChild, ViewContainerRef } from '@angular/core';
import * as $ from 'jquery';
import * as _ from 'lodash';

@Component({
  selector: 'my-table-cell',
  template: '<b (click)="counter++">Counter: {{counter}}, data: {{data.id}}<b>'
})
export class MyTableCellComponent {
  counter = 0;
  data: any;
}

@Component({
  selector: 'my-table',
  template: `
    <hot-table [options]="currentOptions">
    </hot-table>
    <div #templateContainer
        [hidden]="true">
    </div>`,
})
export class MyTableComponent implements OnInit, OnDestroy {

  @ViewChild('templateContainer', { read: ViewContainerRef })
    templateContainer: ViewContainerRef;

  options: ht.GridOptions;
  private cellComponentFactory: ComponentFactory<MyCellComponent>;
  private cellTemplateComponents: {[id: string]:
    ComponentRef<MyTableCellComponent>} = {};

  constructor(private factoryResolver: ComponentFactoryResolver) {};

  public ngOnInit() {
    this.options = { columns: [{
      renderer: this.rendererLinkCell.bind(this),
      data: [{id: 1}, {id: 2}, {id: 3}, {id: 4}]
    }]};
    this.cellComponentFactory = this.factoryResolver
      .resolveComponentFactory(MyTableCellComponent);
  }

  public ngOnDestroy() {
    _.forOwn(this.cellTemplateComponents, (component) => {
      component.destroy();
    });
  }

  private rendererLinkCell(_instance: any, td: Element, _row: number,
      _col: number, _columnKey: string, data: any, _cellProperties) {
    let component = this.cellTemplateComponents[data.id];
    if (!component) {
      component = this.templateContainer
        .createComponent(this.cellComponentFactory);
      _.extend(component.instance, { data });
      component.changeDetectorRef.detectChanges();
      this.cellTemplateComponents[data.id] = component;
    }
    $(td).html(component.location.nativeElement);
  };
}

我还没来得及测试它,所以让我知道它是否有效。