Unable to compile angular component in handsontabl

2019-08-18 17:01发布

Really stuck in a problem, I’m using handsontable with angular2. And in handsontable I’m using cell renderes to populate cells and that cell contains an angular component.

But the problem is that cell is not compiling in angular scope

1条回答
我只想做你的唯一
2楼-- · 2019-08-18 17:52

You will need to compile the component you want to display in the cell and add the component's html to the cell in a custom renderer. Here's an example:

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);
  };
}

I haven't had time to test it, so let me know if it works.

查看更多
登录 后发表回答