首页 > 解决方案 > 将动态创建的自定义 Angular 组件添加到 Nativescript 中的布局

问题描述

我正在尝试将动态创建的自定义 Angular 组件添加到GridLayoutNativeScript 中。我知道如何动态添加默认的非 Angular NativeScript 组件,例如Labelfrom tns-core-modules/ui/label,但它似乎与 Angular 组件的工作方式不同。

我正在关注这篇文章,它描述了如何在纯 Angular 中做到这一点。它似乎几乎可以在 NativeScript 中工作,但并非完全如此。到目前为止,我正在使用这样的模板:

 <GridLayout #grid>
 </GridLayout>

然后在代码中我尝试如下所示:

@ViewChild('grid') gridRef:ElementRef;

public ngAfterViewInit() {

  let grid = this.gridRef.nativeElement;
  grid.addRow(new ItemSpec(1, GridUnitType.AUTO));
  grid.addColumn(new ItemSpec(1, GridUnitType.STAR));

  let componentFactory = this.cfr.resolveComponentFactory(MyCustomComponent);
  let componentRef = componentFactory.create(this.vcr.injector, null, grid);
  componentRef.instance.myproperty = 'some value'; // pass input

  this.appRef.attachView(componentRef.hostView); // add to ng component tree for change detection

  const component = (componentRef.hostView as EmbeddedViewRef<any>).rootNodes[0];
  grid.addChild(component);
}

在最后一步之后,我确实看到网格已经分配了组件所需的空间,但没有任何显示。如果我注释掉最后一步,那么保留的空间确实消失了。我还确认了 rootNodes 数组只有一个元素。

有人知道我可能会错过什么吗?我想问题是如何获取 Angular 视图并将其转换为 NativeScript 视图,这样我就可以执行grid.addChild下面的操作来将新创建的组件分配给特定的行/列。

GridLayout.setRow(component,0); // fix to grid row
GridLayout.setColumn(component,index); // fix to grid column

那将如何工作?

谢谢!

标签: nativescriptangular2-nativescript

解决方案


推荐阅读