简体   繁体   中英

How can i get all images inside of an angular component, including images in children (and children of children…) components

I've tried different css selectors and methods, like

var elements = document.querySelectorAll('#container img');
var elements = this.el.nativeElement.querySelectorAll('img');
var elements = this.el.nativeElement.getElementsByTagName('img');

They all only select in parent component. Is there even a way to achieve this? Something like::ng-deep behaviour.

Just to make it a bit more clear, i want to apply some sort of loading screen for different page sections. Each section is an angular component, which can contain other components of free structure. for the first approach i just want to implement onload handler for every image. This piece of code seems to be working fine, but it only refers to component own images. So, if there is a child component with a huge image inside, my loading screen logic fails:(

const addOnloadToImages = () => {
  const images = this.el.nativeElement.querySelectorAll<HTMLImageElement>('img');
  console.log(`${this.sectionId} images: `, images.length);
  let imagesLoaded = 0;

  if (!images.length) this.domService.sectionImagesLoaded.next(this.sectionId);
  images.forEach(image => {
    image.onload = (event) => {
      imagesLoaded++;
      if (imagesLoaded === images.length) this.domService.sectionImagesLoaded.next(this.sectionId);
    };
  });
}

You can use ContentChild . For example:

@Component({
  selector: `my-component`,
  template: `
    <div #root>
      <img src="" />
      <parent-1>
        <child-with-images></child-with-images>
      </parent-1>
    </div>
  `
})
export class MyComponent implements AfterContentInit {
  @ContentChild('root') rootContainer: ElementRef<HTMLDivElement>;

  ngAfterContentInit() {
    const allImages = this.rootContainer.nativeElement.getElementsByTagName('img');
  }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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