gpt4 book ai didi

Angular 2 : capture events from ng-content

转载 作者:太空狗 更新时间:2023-10-29 17:19:14 27 4
gpt4 key购买 nike

Angular 应用结构:

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

内容组件模板:

<ng-content></ng-content>

内容组件有公共(public)方法show(),但是当我点击这个链接时我得到:

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 上,我不想创建额外的模板或组件。可能我遗漏了一些明显的东西。

Planker

最佳答案

show()将解析为 <app> 的父组件因为它看起来像 <app>是根组件,没有父组件。

我猜这里的错误是 Angular 甚至试图绑定(bind)到点击事件。我的印象是 <ng-content>根本不支持根组件。

另见 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>

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

即使使用 <ng-content> 将内容“传递”到另一个组件并不意味着范围发生变化。 <ng-content>只是一个投影 - 元素显示在不同的地方就是全部,它们仍然由最初添加它们的组件“拥有”。

关于 Angular 2 : capture events from ng-content,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35574220/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com