Component1:我有一个包含ng模板和内容的组件

<ng-template #content><ng-content></ng-content></ng-template>

Directive:在我的指令中,我试图获取templateRef,但它总是空的.(在ViewInit和ContentAfterInit中都try 过)(为了打开模式,我必须将此模板引用传递给服务)

@ViewChild('content') public templateref: TemplateRef<any>;

Usage:

<app-component1 directive1> <app-anothercomponent>.....<app-component2> .... </app-component1>

是否有可能在指令中获取ng模板内容? Slackblitz:https://stackblitz.com/edit/angular-directive-view-children-y59xnh?file=app%2Finput-overview-example.html

推荐答案

我想你是在问我怎么才能从Directive's主机Component那里得到TemplateRef分?

如果事先知道组件的类型,则可以直接从指令中引用它:

export class Directive1Directive implements AfterViewInit {
  constructor(@Host() @Self() private host: Component1Component) {}

  ngAvterViewInit(): void {
    console.log(this.host.templateRef);
  }
}

如果您不知道预期的宿主组件的类型,则会变得更加棘手.一般而言,将主机组件注入指令的最佳方式是让该主机指令实现一个类,并将该组件作为该类提供.

您可以从创建一个具有要引用的宿主构件的所有属性的类开始.在本例中,我们只声明公开TemplateRef的属性.在接口上使用类的唯一原因是它减少了使用InjectionToken的需要.

export abstract class BaseComponent {
  public templateRef?: TemplateRef<any>;
}

主机组件中唯一的问题是,我们需要将一个提供程序添加到它的提供程序数组中,该数组基本上以别名BaseComponent"重新提供"自己.函数forwardRef用于创建对稍后声明的内容的延迟引用.

@Component({
  /*...*/
  providers: [{ provide: BaseClass, useExisting: forwardRef(() => Component1Component ) }]
})
export class Component1Component implements BaseComponent {
  @ViewChild('content') public templateRef?: TemplateRef<any>;
}

该指令基本没有变化.

export class Directive1Directive implements AfterViewInit {
  constructor(private host: BaseComponent) {}

  ngAvterViewInit(): void {
    console.log(this.host.templateRef);
  }
}

这个答案中有很大一部分来自How You Can Access All Host Component Details Inside the Directive in Angular人.

Angular相关问答推荐

Angular v12:Uncatch(in promise):ReferenceError:d3 is not defined ReferenceError:d3 is not defined

具有多重签名的Angular Mocking Service

Change上的Angular 自定义控件无法正常工作

我们应该在Angular 从14升级到15的过程中也升级茉莉花和业力相关的依赖吗?

路由在全局导航中总是给我/甚至使用相对路径

Angular 17不接受带点(.)的路径在开发环境中,它直接抛出一个404错误

更改动态表单控制Angular 的值

Angular 17+独立配置中main.ts bootstrap 调用的最佳实践

RxJS轮询+使用退避策略重试

如何捕获生命周期方法中抛出的Angular组件错误?

ngx-http-client 在 Angular 16 中已弃用

升级到 Ng 16 - npm 错误!对等依赖冲突:@angular/compiler-cli@16.2.1

Observable转换为Observable

在生产模式下使用带Angular 的 livekit

angular 13 ng 构建库失败(ivy部分编译模式)

全局异常处理

在Angular 4中有条件地应用点击事件

在 Angular rxjs 中,我什么时候应该使用 `pipe` 与 `map`

CustomPipe 没有提供者

'ng' 不是内部或外部命令、可运行程序或批处理文件