Angular2:如何用Javascript从index.html中访问DOM-Element(在Component内部

Angular2: How to access DOM-Element (inside Component) from index.html with Javascript

本文关键字:DOM-Element 访问 内部 Component html 何用 Javascript index Angular2      更新时间:2023-09-26

我正试图在我的第一个Angular2-Project (Typescript)中实现伟大的PhotoSwipe-gallery (JavaScript),这真的让我很头疼。

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是一个空对象,所以我想知道这是否有可能访问index.html中的元素,这些元素在Angular2的其他组件中。

另一个原因可能是,我实际上是通过http获取图像的。Get-request,所以也许脚本运行,在'my-gallery'加载之前,但尝试从index.html加载其他元素也失败了。

这是一个非常简化的版本。实际上,我正在运行一个实例化PhotoSwipe-object的脚本。当然,我已经尝试过直接从组件内部运行脚本,显然您不能在组件模板中运行javascript文件。

如果你想让你的内容在元素标签中,你需要在你的模板中插入一个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>

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