首页 > 解决方案 > 如何获取对角度结构指令容器内元素的引用

问题描述

我有以下模板,其中包含一个名为的测试结构指令*appUnless

<h1 *appUnless>
  <app-hello></app-hello>
  <input type="text" value="hello" />
</h1>

在我的结构指令中,到目前为止,我有这个:

import {
  Directive,
  Input,
  TemplateRef,
  ViewContainerRef,
} from "@angular/core";

@Directive({
  selector: "[appUnless]",
})
export class UnlessDirective {
  constructor(
    private templateRef: TemplateRef<any>,
    private viewContainer: ViewContainerRef
  ) {}

  @Input()
  set appUnless(message: string) {
    const embeddedViewRef = this.viewContainer.createEmbeddedView(
      this.templateRef
    );
  }
}

如何input从指令中获取对元素的引用?我希望能够引用与在其input上放置模板引用声明没有什么不同,即,如果我要做<input #myInput>. 显然,由于我不控制放置在容器内的内容,因此我无法#myInput放入模板中。

另外,如何从该指令中获取对具有正确类型的AppHelloComponent(支持的)的引用?app-hello

标签: angularangular-directiveangular-template-variable

解决方案


推荐阅读