I am trying to display a dynamic component similar (not exact) to the example in angular docs.
I have a dynamic directive with viewContainerRef
@Dire
Noted that I face the same problem if directive selector (dynamicComponent in this case) is at :
first element of the component
parent element with *ngIf condition
Hence, I avoid it by put it inside at non-root tag in the component html & load component to viewContainerRef only when the condition match.
You see this error when the directive does not construct. You can set a breakpoint on the directive's constructor and check if the breakpoint ever hits. If not, that means that you are not loading the directive correctly. Then you can check that your component that is loading the directive it is properly adding the directive into the template.
The problem might also be that the selector of the viewRef
(dynamicComponent
in this example) does not match the one specified in the template of the component which uses the componentFactoryResolver
.
You can take this approach:
don't create directive, instead give an Id to ng-template
<ng-template #dynamicComponent></ng-template>
use @ViewChild
decorator inside your component class
@ViewChild('dynamicComponent', { read: ViewContainerRef }) myRef
ngAfterViewInit() {
const factory = this.componentFactoryResolver.resolveComponentFactory(component);
const ref = this.myRef.createComponent(factory);
ref.changeDetectorRef.detectChanges();
}
I ran into this problem as well and the reason was that the location which I wanted to load my component dynamicly into was inside an ng-if that was hidden initially.
<div *ngIf="items">
<ng-template appInputHost></ng-template>
</div>
@ViewChild(InputHostDirective, { static: true }) inputHost: InputHostDirective;
Moving the ng-template to outside the ng-if solved the problem.
In Angular 8 my fix was:
@ViewChild('dynamicComponent', {static: true, read: ViewContainerRef}) container: ViewContainerRef;