单击行后插入动态创建的组件

时间:2018-09-27 11:24:02

标签: javascript angular5 angular-components

我正在研究一种解决方案,其中我想在单击行后追加动态创建的组件

我的表包含带有操作按钮的行,单击这些按钮后,我将调用角度函数并在该行之后加载组件。

这是表代码

<div class="row" *ngFor="let rData of reportData; let i = index;" >
        <div class="col" >
            <button class="btn btn-sm" (click)="loadChildComponent()">+</button>
        </div>
        <div class="col">Name</div>
        <div class="col">Description</div>
        <ng-template #dynamic></ng-template>

</div>

动态组件代码

Service.ts


import { DynamicComponent } from './dynamic.component'
@Injectable()
export class Service {
  factoryResolver;
  rootViewContainer; 
  constructor(@Inject(ComponentFactoryResolver) factoryResolver) {
    this.factoryResolver = factoryResolver
  }
  setRootViewContainerRef(viewContainerRef) {
    this.rootViewContainer = viewContainerRef
  }
  addDynamicComponent() {
    const factory = this.factoryResolver
                        .resolveComponentFactory(DynamicComponent)

    const component = factory
      .create(this.rootViewContainer.parentInjector)

    this.rootViewContainer.insert(component.hostView)
  }
}

这是组件文件。

dynamic.component.ts

import { Component } from '@angular/core'
@Component({
  selector: 'dynamic-component',
  template: `<div class="row"  >
            <div class="col">Data</div>
            <div class="col">Data</div>
            <div class="col">Data</div>
            <div class="col">Data</div>
            <div class="col">Data</div>
            <div class="col">Data</div>
            <div class="col">Data</div>
    <ng-template #dynamic></ng-template>
    </div>`
})
export class DynamicComponent { }

用于呈现动态组件的功能

@ViewChild('dynamic', { 
      read: ViewContainerRef 
    }) viewContainerRef: ViewContainerRef

loadChildComponent() {
        this.service.setRootViewContainerRef(this.viewContainerRef)
        this.service.addDynamicComponent()
    }

现在将其添加到同一div中以用于任何行

我想在点击行后追加它

请帮助。

1 个答案:

答案 0 :(得分:2)

Angular中的ng-template就像一个幽灵元素,即永远不会直接显示。选中此link

更新

因为您一直使用@ViewChild,所以总是在第一行插入模板。 @ViewChild在模板中查找第一个元素。

尝试改用@ViewChildren

请参考以下更改:

<ng-container *ngFor="let rData of reportData; let i = index;">
    <div class="row">
        <div class="col" >
            <button class="btn btn-sm" (click)="loadChildComponent(i)">+</button>
        </div>
        <div class="col">Name</div>
        <div class="col">Description</div>

    </div>
    <div class="row">
        <ng-template #dynamic></ng-template>
    </div>
</ng-container>

JS更改:

@ViewChildren('dynamic', { read: ViewContainerRef }) viewContainerRef: QueryList<ViewContainerRef>

loadChildComponent(index) {
        this.service.setRootViewContainerRef(this.viewContainerRef.toArray()[index])
        this.service.addDynamicComponent()
    }

希望这会有所帮助:)