Unable to compile angular component in handsontable cell

强颜欢笑 提交于 2019-12-11 16:58:36

问题


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:


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.



来源:https://stackoverflow.com/questions/44908970/unable-to-compile-angular-component-in-handsontable-cell

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!