Murhaf Sousli
Murhaf Sousli

Reputation: 13296

Angular 2: get all <img> tags inside specific div

I need a function to get all images inside a specific div, I tried to use BrowserDomAdapter but it's throwing this error el.querySelector is not a function, infact I haven't declared any el variable in my component

import { BrowserDomAdapter} from '@angular/platform-browser/src/browser/browser_adapter';
...
...
constructor(private dom:BrowserDomAdapter){
}
ngAfterContentInit(){
    this.lightboxImages();
}
lightboxImages(){
    let dom = new BrowserDomAdapter();
    let images = dom.querySelector('img','.post-body');
    console.log(images);
}

Update

If I have the <img> tags inside a variable, how can I get the images from it?

export class Post{

   post:Post;

   @Input()
   set data(data:any) {
     this.post = new Post(data); 
     this.lightboxImages(this.post.content());
   }

   lightboxImages(content:any){
       let images = content. ???
       console.log(images);
   }
}

Upvotes: 2

Views: 5352

Answers (2)

Vishesh Mishra
Vishesh Mishra

Reputation: 1108

this.containerBlock.nativeElement.getElementsByTagName("img")

Where containerBlock is template reference. This will return all the img tag inside div with template reference containerBlock.

Upvotes: -1

G&#252;nter Z&#246;chbauer
G&#252;nter Z&#246;chbauer

Reputation: 657138

BrowserDomAdapter is not supposed to be used. It's for Angular internal use only.

I assume you want to query elements passed as children because you use ngAfterContentInit:

@Component({
  ...
  template: `
  ...
  <div #wrapper>
    <ng-content></ng-content>
  </div>
  ...
`
})
export class MyComponent {
  @ViewChild('wrapper') wrapper:ElementRef;
  ngAfterContentInit(){
    this.lightboxImages();
  }
  lightboxImages(){
    let images = this.wrapper.nativeElement.querySelector('img','.post-body');
    console.log(images);
  }
}

Upvotes: 5

Related Questions