我正在研究解决方案,我想在单击行后附加动态创建的组件
我的表由带有操作按钮的行组成,单击该按钮我将调用角度函数并在该行之后加载组件。
这是表代码
<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)
}
}
这是组件文件。
动态组件.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 中
我想在单击行后附加它
请帮忙..
The ng-template
在 Angular 中,它就像一个幽灵元素,即它永远不会直接显示。检查这个link https://angular.io/guide/structural-directives#the-ng-template.
Update:
您始终将模板插入第一行,因为您使用了@ViewChild https://angular.io/api/core/ViewChild。 @ViewChild 查找模板中的第一个元素。
尝试使用@ViewChildren https://angular.io/api/core/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()
}
希望这可以帮助 :)
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)