Angular ng-content:如何在里面找到元素? [英] Angular ng-content: how to find element inside?

查看:24
本文介绍了Angular ng-content:如何在里面找到元素?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个组件,它在 <ng-content> 标签周围声明一些外部 html.但是,如果内容属于特定组件类,或者包含某些标签,我希望能够访问这些内容.

例如,在下面的代码中,组件MyComponent被设置为MyWrapper的内容.从 MyWrapper 内部,如何获取卡在其中的 MyComponent ?

示例

--包装模板--

<代码>...<ng-content #content></ng-content>...

--包装使用--

<我的组件></我的组件></my-wrapper>

我的偏好是能够获得一个表示在 ng-content 中设置的组件的对象,因此我可以使用 typescript 访问它.但是,我会满足于能够获得 DOM 对象.或者,如果我完全走错了路,应该以另一种方式做这件事,我也欢迎.

解决方案

稍微看了下,似乎需要对包装类中的代码稍作调整才能访问 DOM 元素:

代替

<代码>...<ng-content #content></ng-content>...

正如 关于另一个问题的答案 所表明的,必须包装 ng-contentdiv 元素中.然后,使用@ViewChild访问它,如下:

--模板--

<ng-content></ng-content>

--班级--

@ViewChild('content')私人内容;

内容字段将在包装器组件的 AfterViewInit 方法中可用(但不一定在之前):

ngAfterViewInit() {如果(this.content){console.log('内容存在');}if (this.content instanceof MyComponent) {console.log('这应该也可以,但不行.');}}

这样做的一个不足是我还没有找到返回原始组件类的方法.

I have a component that declares some outside html around an <ng-content> tag. However, if the content is of a specific component class, or if it contains certain tags, I'd like to be able to access those.

For example, in the code below, the component MyComponent has been set as the content of MyWrapper. From within MyWrapper, how can I get the MyComponent that has been stuck in it?

Example

--Wrapper Template--

...
<ng-content #content></ng-content>
...

--Wrapper Usage--

<my-wrapper>
  <my-component></my-component>
</my-wrapper>

My preference would be able to get an object representing the component that was set inside the ng-content, so I can access it using typescript. But, I'll settle for just being able to get DOM objects. Or, if I'm totally on the wrong track and should be doing this another way, I'll welcome that too.

解决方案

After reading a bit, it appears that a slight adjustment to the code is necessary in the wrapper class to be able to access the DOM elements:

Instead of

...
<ng-content #content></ng-content>
...

As this answer on a different question indicates, one must wrap the ng-content in a div element. Then, use @ViewChild to access it, as follows:

--Template--

<div #content>
  <ng-content></ng-content>
</div>

--Class--

@ViewChild('content')
private content;

The content field will be available from within the AfterViewInit method in the wrapper component (but not necessarily before):

ngAfterViewInit() {
  if (this.content) {
    console.log('content was present');
  }
  if (this.content instanceof MyComponent) {
    console.log('this should work too, but it doesn't.');
  }
}

A shortfall of this is that I have not discovered a way to get back to the original component class.

这篇关于Angular ng-content:如何在里面找到元素?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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