[英]How to load an Angular2 component directly on the index.html file?
[英]Angular2: How to access DOM-Element (inside Component) from index.html with Javascript
我正在尝试将伟大的PhotoSwipe-gallery (JavaScript) 实现到我的第一个Angular2-Project (Typescript) 中,而这个真的让我头疼。
所以 PhotoSwipe 是用 JavaScript 编写的。 通过实例化,它访问由类名“my-gallery”标记的特定 DOM 元素,并解析所有显然包含图像数据的子元素。
这是我想要实现的一个非常简单的版本:
索引.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
元素。
索引.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; } }
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.