【问题标题】:Dynamically append one component into another component动态地将一个组件附加到另一个组件中
【发布时间】:2018-09-14 11:53:15
【问题描述】:

这是我的 stackblitz 链接:DEMO

当可视化类型为“表”时,我正在尝试将“表”组件附加到应用程序组件的#test 中。为此,我调用createTable() 创建<app-table> 标签并将其附加到#test div 中。

<app-table> 标签存在于 DOM 中,但不存在于 table.component.html 的内容中(即,表格有效!) 这可能是因为它只是一个标签,而不是一个编译的组件。

如何获取应用组件内部显示的表格组件内容?

【问题讨论】:

  • @eko :我试过了,它似乎对我不起作用。这种方法可能出错了。你能帮帮我吗?
  • 您可以在app component html中添加<angular-table></angular-table>
  • @Exterminator:我只想在可视化类型 == 'table' 时附加表格,在特定的迭代中。通过添加标签,表格组件将始终出现。
  • 创建一个全局变量命名类型你想要的任何东西并将*ngif="type === 'table' "添加到<angular-table></angular-table>

标签: javascript angular typescript angular6


【解决方案1】:

试试这个

 createTable() {
    this.container.clear(); 
    const factory = this.resolver.resolveComponentFactory(TableComponent);
    this.componentRef = this.container.createComponent(factory);  

  }

您的分叉示例:https://stackblitz.com/edit/dashboard-inchara-3xrjkj

【讨论】:

  • 我希望表格插入 #charts 而不是另一个 #container
  • 你的意思是在div里面?
  • 是的。里面
  • 将 ng-template 移动到该 div 内检查 stackblitz
  • 这样做,只追加一次表格组件。请检查 appObject,visualization type == table 是两次,这意味着 graph-graph-table-graph-table 应该出现在 DOM 中。检查我的 stackblitz 输出以查看 app-table 标记根据条件插入两次
【解决方案2】:

使用ComponentFactoryResolver 动态添加组件。这在Angular Docs 中有进一步的解释。在 stackblitz 中添加了完整的解决方案: ComponentFactoryResolver。总之,这就是我所做的:

app.component.ts中创建表:

createTable(container) {
  let componentFactory = this.componentFactoryResolver.resolveComponentFactory(TableComponent);
  let viewContainerRef = this.insTable.viewContainerRef;
  viewContainerRef.clear();
  let componentRef = viewContainerRef.createComponent(componentFactory);
  // let e = document.createElement("app-table");
  // container.appendChild(e);
}

用作和锚点的指令table.directive.ts

import { Directive, ViewContainerRef } from '@angular/core';

@Directive({
  selector: '[ins-table]',
})
export class TableDirective {
  constructor(public viewContainerRef: ViewContainerRef) { }
}

还有app.component.html

<div #charts id="test">
  <ng-template ins-table></ng-template>
</div>

app.module.ts 带有适当的声明以使其一切正常:

import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { ChartModule } from 'angular-highcharts';

import { AppComponent } from './app.component';

import { HttpClientModule } from '@angular/common/http';
import { TableComponent } from './table/table.component';
import { TableDirective } from './table/table.directive';

@NgModule({
  imports: [BrowserModule, ChartModule, HttpClientModule],
  declarations: [AppComponent, TableComponent, TableDirective],
  bootstrap: [AppComponent],
  providers: [HttpClientModule],
  entryComponents: [
    TableComponent
  ]
})
export class AppModule { }

【讨论】:

猜你喜欢
  • 1970-01-01
  • 2018-05-27
  • 1970-01-01
  • 1970-01-01
  • 2022-10-25
  • 2020-01-05
  • 2020-03-12
  • 1970-01-01
  • 2018-05-18
相关资源
最近更新 更多