2016-09-20 7 views
1

PhotoSwipe-gallery(JavaScript)を私の最初のAngular2-Project(Typescript)に実装しようとしています。私は頭痛。Angular2:Javascriptを使ってindex.htmlからDOM-Elementにアクセスする方法

PhotoSwipeはJavaScriptで書かれています。インスタンス化によって、はクラス名 'my-gallery'によってタグ付けされた特定のDOM要素にアクセスし、明らかに画像データを含むすべての子要素を解析します。ここで

は私が達成しようとしているものの非常にシンプルなバージョンです:上記のバージョン

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> 

myGalleryは空のオブジェクトであるので、私はかしらこれにより、Angular2の他のコンポーネントの内側にあるindex.htmlの要素にアクセスすることができます。

もう1つの理由は、実際にはhttp.get-requestで自分の画像を取得することができるため、スクリプトが実行されてから 'my-gallery'が読み込まれた後にindex.htmlから他の要素を読み込もうとします失敗しました。

これは非常に単純化されたバージョンです。実際には、私はPhotoSwipeオブジェクトをインスタンス化するスクリプトを実行しています。 もちろん、コンポーネント内からスクリプトを直接実行しようとしましたが、コンポーネントテンプレート内でJavaScriptファイルを実行することはできません。

ヘルプは高く評価されています。

+0

あなたのスクリプトは、テンプレートの読み込みの前に実行されます。なぜあなたはそれのための適切なコンポーネントを作成しないのですか?そして、あなたは 'ngAfterViewInit'フックの中でスクリプトを呼び出すことができます。 – yurzui

答えて

1

コンテンツを要素タグ内に収めるには、ng-content要素をテンプレートに挿入する必要があります。

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>

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

関連する問題