如何在 Angular 6 中选择原生元素的 ContentChild? [英] How do I select a ContentChild of a native element in Angular 6?

查看:33
本文介绍了如何在 Angular 6 中选择原生元素的 ContentChild?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个使用内容投影的组件.

I have a component that uses content projection.

<ng-content select="button">
</ng-content>

我想在我的组件中做这样的事情:

I want to do something like this in my component:

@ContentChild('button') button: ElementRef;

然而,当我检查 this.button 时,它在 ngAfterViewInitngAfterContentInit 中都是 undefined.

However, when I check this.button, it is undefined both in ngAfterViewInit and ngAfterContentInit.

如果我的内容子元素是原生元素而不是自定义组件,我该如何选择它?

How can I select my content child if it is a native element and not a custom component?

推荐答案

需要了解的重要一点是,您传递给 @ContentChild 的选择器不是 CSS 选择器,并且您无法根据其 ID、类或元素类型找到内容子项.您只能搜索使用 # 运算符指定的标识符名称.

The important thing to understand is that the selector you pass to @ContentChild is not a CSS selector, and you cannot find a content child based on its ID, class or element type. You can only search on the identifier name you gave it using the # operator.

因此给定一个名为 my-comp 的组件和以下用法:

So given a component called my-comp and the following usage:

<my-comp><button #buttonName>Click me</button></my_comp>

您可以使用:

@ContentChild('buttonName') button: ElementRef;

编辑

正如 OP 对 ckTag 回答的评论中所指出的(他比我领先一分钟),这确实意味着调用代码需要知道您希望内容被标记为特定名称.

As noted in the OP's comment on ckTag's answer (he beat me to it by a minute), that does mean the calling code will need to know you expect the content to be tagged with a specific name.

如果您的组件确实需要了解其子内容的详细信息,则更好的答案实际上是向 @ContentChild 提供指令类型:

If your component does actually need to know detail of its content children, the better answer is actually to provide the directive type to @ContentChild:

@ContentChild(MyButtonComponent, { read: ElementRef })
button: ElementRef;

这也更好,因为您现在可以实际期望知道内容的类型;毕竟,调用代码可以将 #button 粘贴到 div 上,如果感觉如此.

This is also better, because you can now realistically expect to know the type of content; the calling code can stick #button on a div if it feels like it, after all.

这确实意味着告别使用常规 HTML button 元素,但还有其他好处.例如,您可以提供一条消息来指导您的调用代码,如下所示:

That does mean saying goodbye to using a regular HTML button element, but comes with other benefits. You could, for example, provide a message to guide your calling code, like this:

<ng-content></ng-content>
<div *ngIf="button">Error: Please provide a MyButtonComponent</div>

这篇关于如何在 Angular 6 中选择原生元素的 ContentChild?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆