角度应用程序结构:
<app><div content><a href="#" (click)="show()">click me</a></div></app>
Run Code Online (Sandbox Code Playgroud)
内容组件模板:
<ng-content></ng-content>
Run Code Online (Sandbox Code Playgroud)
内容组件有公共方法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
Run Code Online (Sandbox Code Playgroud)
基本上我想重用页面标记并将侦听器放在现有的dom上,我不想创建额外的模板或组件.可能我错过了一些明显的东西.
show()
将解析为父组件,<app>
因为它看起来像是<app>
根组件,没有父组件.
我想这里的错误是Angular甚至试图绑定到click事件.我得到了<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>
Run Code Online (Sandbox Code Playgroud)
绑定在声明它们的组件中解析.在上面的示例中,我ContentComponent
通过#contentRef
在目标元素上创建模板变量并在定义单击处理程序时引用它来显式地重定向引用(click)="contentRef.show($event)"
.
即使内容被"传递"到另一个组件使用<ng-content>
并不意味着范围发生变化.<ng-content>
只是一个投影 - 元素显示在不同的地方就是全部,它们仍然由最初添加它们的组件"拥有".
归档时间: |
|
查看次数: |
5424 次 |
最近记录: |