Angular2:如何获取子组件中ViewChild的引用 [英] Angular2: How to get a reference to a ViewChild in a child component

查看:85
本文介绍了Angular2:如何获取子组件中ViewChild的引用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个组件( App ),其中包含另一个组件( Comp )。 App 从数据库中获取字符串内容并通过 @Input()转发给 Comp 。此字符串内容可以包含h​​tml标签,例如

I have a component (App) that contains another component (Comp). App gets string content from a database and forwards it by @Input() to Comp. This string content can contain html tags like

Some text before <a>Click</a> Some Text after

Comp 这个内容是应该被渲染,并且应该添加一些事件监听器。因此,使用 [innerHtml] 添加此内容。因为(点击) [innerHtml] 中删除​​了对 a 标签,并且应该使用 addEventListener 添加事件监听器。但我找不到引用 a 标记的方法,因为 ElementRef 到组件不包含 nativeElement

In Comp this content is supposed to be rendered and some event listeners are supposed to be added. Therefor this content is added using [innerHtml]. Because (click) is removed in [innerHtml] a reference to the a tag is needed and a event listener is supposed to be added with addEventListener. But I can't find a way to reference the a tag since an ElementRef to a component doesn't contain nativeElement.

让这个plunker运行的最佳方法是什么?
https://plnkr.co/edit/xVUu0LJ02YVnBO25Zr4j?p=preview

What is the best way to get this plunker running? https://plnkr.co/edit/xVUu0LJ02YVnBO25Zr4j?p=preview

推荐答案

Angular2不鼓励直接访问DOM

这是一种使用直接dom访问的hacky方法。

Here's a hacky way to do it with direct dom access.

在子comp中定义事件监听器并过滤事件:

Define an event listener in the child comp and filter the event:

document.querySelector('body').addEventListener('click', function(event) {
      if (event.target.tagName.toLowerCase() === 'a') {
         that.updateCounter.next(true);
      }
    });

然后使用 EventEmitter 来更新计数器。

then use an EventEmitter to update the counter.

Plunker: https:// plnkr.co/edit/vm44niH781j4mEQHDpLU?p=preview

这篇关于Angular2:如何获取子组件中ViewChild的引用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆