Angular structural directive: wrap a node element with some other component

I have the simplest Angular structural directive:

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

@Directive({ selector: '[hello]' })
export class HelloDirective {
  constructor(
    private templateRef: TemplateRef<any>, private viewContainer: ViewContainerRef) {
      this.viewContainer.createEmbeddedView(this.templateRef);
  }
}

I use it as follows:

<div *hello>Hello Directive</div>

It shows me the message "Hello Directive" as expected. Now I want to change the content by wrapping it with some other component:

<my-component>Hello Directive</my-component>

And I want the directive to do this for me. I know that I can use the Component paradigm and create HelloComponentinstead HelloDirectiveand use ng-template, etc. With a template defined by a property templateor templateUrlon a decorator @Component... But is there an approach that can be used with the directive paradigm to achieve such a result?

+4
source share
1 answer

. ,

@Directive({ selector: '[hello]' })
export class HelloDirective {
  constructor(
      private templateRef: TemplateRef<any>,
      private viewContainer: ViewContainerRef,
      private resolver: ComponentFactoryResolver) {
  }

  ngOnInit() {
    const templateView = this.templateRef.createEmbeddedView({});
    const compFactory = this.resolver.resolveComponentFactory(MyComponent);
    this.viewContainer.createComponent(
      compFactory, null, this.viewContainer.injector, [templateView.rootNodes])
  }
}

MyComponent entryComponents @NgModule

Stackblitz

.

+6

Source: https://habr.com/ru/post/1689488/


All Articles