In Parent Component.ts
@ViewChild('dynamic', {
read: ViewContainerRef
}) viewContainerRef: ViewContainerRef;
In HTML code
<div cdkDropList class="example-container" (cdkDropListDropped)="drop($event)">
<div class="example-box" *ngFor="let item of testSelector" cdkDrag>
<div class="title">{{item.key}}</div>
<div class="content" [innerHTML]="item.value | safeHtml">
</div>
</div>
</div>
<ng-template #dynamic></ng-template>
This work fine but when nested inside dive
<div cdkDropList class="example-container" (cdkDropListDropped)="drop($event)">
<div class="example-box" *ngFor="let item of testSelector" cdkDrag>
<div class="title">{{item.key}}</div>
<div class="content" [innerHTML]="item.value | safeHtml">
<ng-template #dynamic></ng-template>
</div>
</div>
</div>
viewContainerRef is undefined?
Component.ts
@Component({
....
})
export class TestComponent implements OnInit, AfterViewInit {
@ViewChild('dynamic', {
read: ViewContainerRef
}) viewContainerRef: ViewContainerRef;
constructor(@Inject(Service) private service) {
}
ngAfterViewInit() {
this.service.setRootViewContainerRef(this.viewContainerRef);
this.service.addDynamicComponent();
}
}
and service.ts
@Injectable()
export class Service {
factoryResolver: any;
rootViewContainer: any;
constructor(
@Inject(ComponentFactoryResolver)
factoryResolver) {
this.factoryResolver = factoryResolver;
}
setRootViewContainerRef(viewContainerRef) {
this.rootViewContainer = viewContainerRef;
}
addDynamicComponent() {
const factory = this.factoryResolver
.resolveComponentFactory(JobDashComponent);
const component = factory
.create(this.rootViewContainer.parentInjector);
this.rootViewContainer.insert(component.hostView);
}
}
viewContainerRef?viewContainerRef.