简体   繁体   English

在 Angular 11 中投影内容时,是否可以获得对模板变量标识的元素的引用?

[英]When projecting contents in Angular 11, is it possible to get a reference to elements identified by a template variable?

I have a scenario where Component A projects some elements into Component B. I would like to display all such elements, and get a reference to elements identified by template variables (#content, #button).我有一个场景,其中组件 A 将一些元素投射到组件 B 中。我想显示所有这些元素,并获取对模板变量(#content、#button)标识的元素的引用。

Component A's template:组件 A 的模板:

<app-component-b>
  <div #content></div>
  <button #button></button>
</app-component-b>

Component B's template:组件 B 的模板:

<ng-content></ng-content>

From Component B, is it possible to get a reference to the #content and #button elements?从组件 B 中,是否可以获得对#content#button元素的引用?


EDIT: Before posting I'd tried with ViewChild and ContentChild at OnInit time, but I wasn't getting anything back, which made me question if it even was possible.编辑:在发布之前,我在 OnInit 时间尝试过使用 ViewChild 和 ContentChild,但我没有得到任何回报,这让我怀疑它是否可能。 I tried fiddling with it a bit more, and it looks like it works with @ContentChild at AfterViewInit time.我试着再摆弄一下,看起来它在 AfterViewInit 时间与 @ContentChild 一起工作。

It looks like this is achievable at least from AfterContentInit using @ContentChild.看起来这至少可以通过使用 @ContentChild 的 AfterContentInit 来实现。

export class ComponentB implements OnAfterContentInit {

    @ContentChild('content') content: HTMLDivElement;
    @ContentChild('button') button: HTMLButtonElement;

    ngAfterContentInit(): void {
        // --> ElementRef, ElementRef
        console.log(this.content, this.button);
    }

}

I do not know if this is good practice or a good solution though.我不知道这是一个好的做法还是一个好的解决方案。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM