【发布时间】:2023-01-28 12:46:07
【问题描述】:
自 Angular 版本 15 以来,有可能将独立指令绑定到组件和指令装饰器。有没有办法将结构指令(注入 templateRef)用作 hostDirective?这将非常有用,但无论如何我都尝试过,但我总是找不到 TemplateRef 的提供者。
【问题讨论】:
自 Angular 版本 15 以来,有可能将独立指令绑定到组件和指令装饰器。有没有办法将结构指令(注入 templateRef)用作 hostDirective?这将非常有用,但无论如何我都尝试过,但我总是找不到 TemplateRef 的提供者。
【问题讨论】:
在您提供的演示中,您在非独立组件中使用standalone指令,在本例中HelloComponent包含在AppModule中,因此为了使用您的directive,您需要导入imports 数组,就像它是一个 module
@NgModule({
imports: [BrowserModule, FormsModule, MyIfDirective], // directive here
declarations: [AppComponent, HelloComponent],
bootstrap: [AppComponent],
})
export class AppModule {}
如果 HelloComponent 是 standalone,那么您需要将其导入组件的元数据 imports 数组。
【讨论】:
you need to update your directive.ts :
import {
Directive,
Injectable,
TemplateRef,
ViewContainerRef,
} from '@angular/core';
@Injectable({
providedIn: 'root',
})
@Directive({
selector: '[myIf]',
standalone: true,
})
export class MyIfDirective {
constructor(private tpl: TemplateRef<any>, private vcr: ViewContainerRef) {}
ngOnInit() {
this.vcr.createEmbeddedView(this.tpl);
}
}
【讨论】: