因此,我在自己的文件中定义了以下内容,其中包含父级和子级组件:
父级
/// <reference path="angular2/typings/browser.d.ts" />
/// <reference path="angular2/core.d.ts" />
import {bootstrap} from 'angular2/platform/browser';
import {Component} from 'angular2/core';
@Component({
selector: 'parent',
template:
'<div>
<ng-content></ng-content>
</div>'
})
export class Parent{
parentDiagnostic(){
return "this is the parent scope!";
}
}
bootstrap(Parent);
孩子
/// <reference path="angular2/typings/browser.d.ts" />
/// <reference path="angular2/core.d.ts" />
import {bootstrap} from 'angular2/platform/browser';
import {Component} from 'angular2/core';
@Component({
selector: 'child',
template:
'<div>
<h1>{{parentDiagnostic()}}</h1>
<h1>{{childDiagnostic()}}</h1>
</div>'
})
export class Child{
childDiagnostic() {
return "this is a child!";
}
}
bootstrap(Child);
我这样使用的:
<parent>
<child></child>
</parent>
为什么parentDiagnostic()在子范围内有效,而childDiagnostic()无效?不应该相反吗?父母和孩子不需要沟通,但是html是嵌入式的。您如何解决这个问题?
ng-content
没有记录,但是有很多非常简单的例子却很容易引起误解。
ng-content
是组件模板中的投影目标,投影内容本身属于声明它的模板,所有模板变量和方法也是如此。
在您的情况下,根模板是直接在html页面上声明的,因此其所有者是Parent组件(作为最顶层的组件),因此所有模板var都针对Parent组件进行了解析。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句