Angular structural directive: wrap the host element with some another component

前端 未结 1 561
旧时难觅i
旧时难觅i 2021-02-13 18:22

I have simplest Angular structural directive:

import { Directive, TemplateRef, ViewContainerRef } from \'@angular/core\';
         


        
相关标签:
1条回答
  • 2021-02-13 18:49

    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

    • Creating a angular2 component with ng-content dynamically
    0 讨论(0)
提交回复
热议问题