Angular 8 组件指令问题 html
Angular 8 issue with directive on component html
我使用 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"
我该如何解决这个问题?
由于您的选择器是 appDynamic,因此您需要使用它来设置指令。
<ng-template #sider="dynamicdirective" appDynamic></ng-template>
我使用 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"
我该如何解决这个问题?
由于您的选择器是 appDynamic,因此您需要使用它来设置指令。
<ng-template #sider="dynamicdirective" appDynamic></ng-template>