组件html指令的Angular 8问题

时间:2019-07-16 19:41:31

标签: angular typescript angular8

我已经使用angular 8创建了一条指令。

指令代码:

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

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

  constructor(public viewContainerRef: ViewContainerRef) { }

}

然后我将其添加到我的ts文件中:

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);
  }

}

最后,我将代码添加到组件的html中,这是我收到错误的地方:

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

上面的代码行给了我以下错误:

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

我该如何解决?

1 个答案:

答案 0 :(得分:1)

由于选择器是appDynamic,因此需要使用该参数设置指令。

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