user11287150
user11287150

Reputation:

Angular 8 issue with directive on component html

I have created a directive using angular 8.

Directive code:

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

@Directive({
  selector: '[appDynamic]',
  exportAs: 'dynamicdirective'
})
export class DynamicDirective {

  constructor(public viewContainerRef: ViewContainerRef) { }

}

Then I added it to my component ts file:

import { Component, OnInit, ComponentFactoryResolver, ViewChild } from '@angular/core';

@Component({
  selector: 'app-preview',
  templateUrl: './preview.component.html',
  styleUrls: ['./preview.component.scss']
})
export class PreviewComponent implements OnInit {

  @ViewChild('sider', {static: true})
  sider;

  constructor(private componentFactoryResolver: ComponentFactoryResolver) {
  }

  ngOnInit() {
    const componentFactory = this.componentFactoryResolver.resolveComponentFactory(PreviewComponent);
    this.sider.viewContainerRef.createComponent(componentFactory);
  }

}

And finally I added the code to the component's html which is where I'm getting the error:

<ng-template #sider="dynamicdirective" dynamic></ng-template>

The line of code above is giving me the following error:

There is no directive with "exportAs" set to "dynamicdirective"

How can I fix this?

Upvotes: 2

Views: 1742

Answers (1)

abney317
abney317

Reputation: 8512

Since your selector is appDynamic, you need set the directive with that.

<ng-template #sider="dynamicdirective" appDynamic></ng-template>

Upvotes: 1

Related Questions