Use Directive to get its ViewContainerRef instead of using @ViewChild

Use Directive to get its ViewContainerRef instead of using @ViewChild

//our root app component
import {Component, NgModule, Inject, Directive, ViewContainerRef, ComponentFactoryResolver, ViewChild, VERSION} from '@angular/core'
import {BrowserModule} from '@angular/platform-browser'

@Directive({
  selector: '[app-component-container]',
})

export class AppComponentContainer {
  constructor(vc: ViewContainerRef, @Inject('app-component-service') shared) {
    shared.registerContainer(vc);
  }
}

@Component({
  selector: 'a-comp',
  template: `
      <span>I am A component</span>
  `,
})
export class AComponent {
}

const shared = {
  createListeners: [],
  destroyListeners: [],
  onContainerCreated(fn) {
    this.createListeners.push(fn);
  },
  onContainerDestroyed(fn) {
    this.destroyListeners.push(fn);
  },
  registerContainer(container) {
    this.createListeners.forEach((fn) => {
      fn(container);
    })
  },
  destroyContainer(container) {
    this.destroyListeners.forEach((fn) => {
      fn(container);
    })
  }
};

@Component({
  selector: 'my-app',
  providers: [
    {
      provide: 'app-component-service',
      useValue: shared
    }
  ],
  template: `
      <h1>I am parent App component</h1>
      <div class="insert-a-component-inside">
          <ng-container app-component-container></ng-container>
      </div>
  `,
})
export class AppComponent {
  vc: ViewContainerRef;

  constructor(private r: ComponentFactoryResolver, @Inject('app-component-service') shared) {
    shared.onContainerCreated((container) => {
      this.vc = container;
      const factory = this.r.resolveComponentFactory(AComponent);
      this.vc.createComponent(factory);
    });

    shared.onContainerDestroyed(() => {
      this.vc = undefined;
    })
  }
}

@NgModule({
  imports: [BrowserModule],
  declarations: [AppComponent, AComponent, AppComponentContainer],
  entryComponents: [AComponent],
  bootstrap: [AppComponent]
})
export class AppModule {
}

https://hackernoon.com/here-is-how-to-get-viewcontainerref-before-viewchild-query-is-evaluated-f649e51315fb

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.