David Gregor
David Gregor

Reputation: 55

Inject components with a directive into a referenced element (Angular 12)

Now I inject my extra components to my main component's root level in a directive, with this approach:

@Directive({
  selector: '[my-controls]',
})
export class MyControlsDirective implements OnInit, OnDestroy {
  constructor(
    @Inject(ComponentFactoryResolver) private factoryResolver: ComponentFactoryResolver,
    private viewContainerRef: ViewContainerRef,
  ) {}
  ngOnInit() {
    this.viewContainerRef.createComponent(
      this.factoryResolver.resolveComponentFactory(MyControlComponent),
      undefined,
      this.viewContainerRef.injector
    );
}

This worked fine, but after a structure change, i need to insert these components into div in the template. It is the 'appContainer' div. I cannot reach the ViewChild in the diretive, only in the component, so i got lost the approaches. I tried to redirect my directive with exportAs, but it did not work. I hope there is a simple way to reach the div in the directive. I would not change my directives into inputs, because it would be a breaking change. So how could i inject the MyControlComponent into the appContainer with MyControlsDirective?

...
<ng-template #simpleApp>
  <div class="inner-app" id="myApp" #appContainer>
   ...
  </div>
</ng-template>

Upvotes: 0

Views: 262

Answers (1)

vimala vinisha
vimala vinisha

Reputation: 1

I think you are facing an issue to use viewContainerRef inside directive file due to recent breaking changes. You can try to set this vcf value as a input from appComponent Or can set it from subscriber component where you are going to inject this directive.

Thanks

Upvotes: 0

Related Questions