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

标签 javascript html dom angular typescript

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

所以 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 对象的脚本。 当然,我尝试直接从组件内部运行脚本,显然您无法在组件模板内运行 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;
    }
}

关于javascript - Angular2 : How to access DOM-Element (inside Component) from index. html 与 Javascript,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39601105/

相关文章:

javascript - 使用纯 JavaScript 交换默认字段值

html - :hover affects text hyperlinks, 但不是 img 超链接

java - 从 DOM 中删除节点

javascript - 是否可以从外部样式表中提取所有样式并将它们放在同一页面上?

php - CData section not finished 问题

javascript - 异步函数作为 setInterval Nodejs 的参数

javascript - 如何防止SVG文字流出其圆圈?

javascript - Angular JS - 如何强制浏览器记录历史记录以进行快速路由?

javascript - 调整 :hover in a carousel 上的 CSS 图像 mask

html - carousel - 将 caroseul 设置为固定高度并防止图像向外拉伸(stretch)