【问题标题】:Angular 15+ No provider for TemplateRef when structural directive used as hostDirective当结构指令用作 hostDirective 时,Angular 15+ 没有 TemplateRef 的提供者
【发布时间】:2023-01-28 12:46:07
【问题描述】:

自 Angular 版本 15 以来,有可能将独立指令绑定到组件和指令装饰器。有没有办法将结构指令(注入 templateRef)用作 hostDirective?这将非常有用,但无论如何我都尝试过,但我总是找不到 TemplateRef 的提供者。

stackblitz to play

【问题讨论】:

    标签: angular angular15


    【解决方案1】:

    在您提供的演示中,您在非独立组件中使用standalone指令,在本例中HelloComponent包含在AppModule中,因此为了使用您的directive,您需要导入imports 数组,就像它是一个 module

    @NgModule({
      imports: [BrowserModule, FormsModule, MyIfDirective], // directive here
      declarations: [AppComponent, HelloComponent],
      bootstrap: [AppComponent],
    })
    export class AppModule {}
    

    如果 HelloComponentstandalone,那么您需要将其导入组件的元数据 imports 数组。

    【讨论】:

      【解决方案2】:
      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);
        }
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2018-06-21
        • 2018-05-01
        • 2016-06-26
        • 2015-08-15
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2017-10-12
        相关资源
        最近更新 更多