I have simplest Angular structural directive:
import { Directive, TemplateRef, ViewContainerRef } from \'@angular/core\';
You can create component dynamically and pass projectable nodes to it. So it could look like
@Directive({ selector: '[hello]' })
export class HelloDirective implements OnInit, DoCheck {
templateView: EmbeddedViewRef<any>;
constructor(
private templateRef: TemplateRef<any>,
private viewContainer: ViewContainerRef,
private resolver: ComponentFactoryResolver) {
}
ngOnInit() {
this.templateView = this.templateRef.createEmbeddedView({});
const compFactory = this.resolver.resolveComponentFactory(MyComponent);
this.viewContainer.createComponent(
compFactory, null, this.viewContainer.injector, [this.templateView.rootNodes])
}
ngDoCheck(): void {
if (this.templateView) {
this.templateView.detectChanges();
}
}
}
You have to add MyComponent
to entryComponents
array of your @NgModule
Complete example can be found on Stackblitz
See also