1

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.

1
  • Your script is executed before template loading. Why you don't create appropriate component for that? And so you can invoke script inside ngAfterViewInit hook. Commented Sep 20, 2016 at 18:47

1 Answer 1

1

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;
    }
}

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.