在一个组件内,angualr如何获取双重for循环包括的img标签的dom
时间: 2024-05-29 07:10:52 浏览: 18
可以使用`ViewChild`来获取包含这些img标签的DOM元素。
首先,在组件类中定义一个视图子元素引用变量,如下所示:
```typescript
import { Component, ViewChild, ElementRef } from '@angular/core';
@Component({
selector: 'app-my-component',
template: `
<div #myDiv>
<div *ngFor="let item of items">
<div *ngFor="let img of item.images">
<img src="{{img.url}}">
</div>
</div>
</div>
`
})
export class MyComponent {
@ViewChild('myDiv') myDiv: ElementRef;
items = [
{
images: [
{url: 'https://example.com/image1.jpg'},
{url: 'https://example.com/image2.jpg'}
]
},
{
images: [
{url: 'https://example.com/image3.jpg'},
{url: 'https://example.com/image4.jpg'}
]
}
];
}
```
在这个组件中,我们定义了一个名为`myDiv`的`ViewChild`,它会引用`<div>`元素。我们还定义了一个`items`数组,其中包含包含图片的对象。这个组件使用`*ngFor`指令来循环遍历这个数组,并在每个对象中使用`*ngFor`指令来遍历包含的图片数组。每个图片都是一个`<img>`标记,其中`src`属性绑定到对象中的`url`属性。
在组件类中,我们可以通过`myDiv.nativeElement`属性来访问`<div>`元素的本机DOM对象。我们可以使用这个对象来查找包含的所有`<img>`元素,如下所示:
```typescript
ngAfterViewInit() {
const imgEls = this.myDiv.nativeElement.querySelectorAll('img');
console.log(imgEls);
}
```
在这个例子中,我们在`ngAfterViewInit`生命周期钩子中访问了`myDiv`元素的本机DOM对象,并使用`querySelectorAll`方法查找所有的`<img>`元素。我们将它们存储在`imgEls`变量中,并使用`console.log`方法将它们输出到控制台。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)