Angular 2:从ng-content捕获事件 [英] Angular 2: capture events from ng-content

查看:98
本文介绍了Angular 2:从ng-content捕获事件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

角度应用程序结构:

<app><div content><a href="#" (click)="show()">click me</a></div></app>

内容组件模板:

<ng-content></ng-content>

内容组件具有公共方法show(),但是当我单击此链接时,我得到:

Content component has public method show(), but when i click this link i get:

Error: EXCEPTION: Error during evaluation of "click"
ORIGINAL EXCEPTION: TypeError: l_context.show is not a function
ORIGINAL STACKTRACE:
anonymous/ChangeDetector_AppComponent_0.prototype.handleEventInternal@http://localhost:3000/node_modules/angular2/bundles/angular2.dev.js line 10897 > Function:207:13
AbstractChangeDetector</AbstractChangeDetector.prototype.handleEvent@http://localhost:3000/node_modules/angular2/bundles/angular2.dev.js:8788:17

基本上,我想重用页面标记并将侦听器放在现有的dom上,我不想创建其他模板或组件.可能我缺少明显的东西.

Basically i want to reuse page markup and put listeners on existing dom, i don't want to create additonal templates or components. Probably i'm missing something obvious.

Planker

推荐答案

show()将解析为<app>的父组件,并且因为看起来<app>是根组件,所以没有父组件.

show() would resolve to the parent component of <app> and because it looks like <app> is the root component, there is no parent.

我猜这里的错误是Angular甚至试图绑定到click事件. 我的印象是根组件完全不支持<ng-content>.

I guess the bug here is that Angular even tries to bind to the click event. I got the impression that <ng-content> isn't supported at all on the root component.

另请参见 https://github.com/angular/angular/issues/1858( https://github.com/angular/angular/issues/6046 )

更新

<h1>Angular</h1>
<div content #contentRef>
    <ui>
        <li><a href="#" (click)="contentRef.show($event)" class="link" button>link 1</a></li>
        <li><a href="#" (click)="contentRef.show($event)" class="link" button>link 2</a></li>
        <li><a href="#" (click)="contentRef.show($event)" class="link" button>link 3</a></li>
    </ui>
</div>

绑定在声明它们的组件内解析.在上面的示例中,我通过在目标元素上创建模板变量#contentRef并在定义单击处理程序(click)="contentRef.show($event)"时对其进行引用,将引用显式重定向到ContentComponent.

bindings are resolved within the component where they are declared. In the above example I explicitly redirected the reference to the ContentComponent by creating a template variable #contentRef on the target element and referring it when defining the click handler (click)="contentRef.show($event)".

即使使用<ng-content>将内容传递"到另一个组件也不意味着范围会更改. <ng-content>仅仅是一个投影-元素全部显示在不同的位置,它们仍然由最初添加它们的组件拥有".

Even though the content is "passed" to another component using <ng-content> doesn't mean the scope changes. <ng-content> is only a projection - the elements are displayed at a different place is all, they are still "owned" by the component where they are added originally.

这篇关于Angular 2:从ng-content捕获事件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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