Reputation: 443
I am trying to implement the great PhotoSwipe-gallery (JavaScript) into my very first Angular2-Project (Typescript), and this one really gives me headache.
So PhotoSwipe is written in JavaScript. By it's instantiation it accesses a specific DOM-element tagged by the classname 'my-gallery' and parses all child-elements which obviously contain the image-data.
Here is a very simple version of what I am trying to achieve:
index.html
<body>
<my-app>
<router-outlet></router-outlet>
<my-images>
<div class="my-gallery">
<-- images -->
</div>
</my-images>
<my-app>
<script>
<--Want Access to class 'gallery' -->
myGallery = document.querySelectorAll('my-gallery');
</script>
<body>
In the above version myGallery is an empty object, so I wonder if this it is possible to gain access to elements from index.html, that are inside of other components in Angular2.
Another reason could be, that I actually get my images by an http.get-request, so maybe the script runs, before 'my-gallery' was loaded, but attempts to load other elements from index.html have also failed.
This is a very simplified version. In reality I am running a script that instantiates the PhotoSwipe-object. Of course I have tried to run the script from inside the component directly, apperently you can't run JavaScript-files inside a components-template.
Help is highly appreciated.
Upvotes: 1
Views: 6083
Reputation: 7919
If you want your content to be inside the element tags you need to insert a ng-content
element in your templates.
index.html
<body>
<my-app>
<router-outlet></router-outlet>
<my-images>
<div ref-myGallery class="my-gallery">
<-- images -->
</div>
</my-images>
<my-app>
<script>
<--Want Access to class 'gallery' -->
myGallery = document.querySelectorAll('my-gallery');
</script>
<body>
my-image.component.ts
import { Component, ContentChild, ElementRef, AfterContentInit } from '@angular/core';
@Component({
selector: 'my-images',
template: `<ng-content></ng-content>`,
})
export class MyImageComponent implements AfterContentInit {
@ContentChild('myGallery', { read: ElementRef }) myGalleryEl: ElementRef;
ngAfterContentInit() {
var myGallery = this.myGalleryEl.nativeElement;
}
}
Upvotes: 1