简体   繁体   English

带有打字稿和 ng-content 的 angular2,我的范围是什么?

[英]angular2 with typescript and ng-content, what's my scope?

So i have something like the following with a parent and child component defined in their own files:所以我有类似下面的东西,在他们自己的文件中定义了一个父组件和子组件:

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: 'parent',
    template:
    '<div>
        <ng-content></ng-content>
    </div>'
})
export class Parent{
    parentDiagnostic(){
        return "this is the parent scope!";
    }
}

bootstrap(Parent);

Child孩子

/// <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);

Which i use like this:我像这样使用:

<parent>
    <child></child>
</parent>

Why is parentDiagnostic() valid in child scope but childDiagnostic() is not?为什么 parentDiagnostic() 在子范围内有效而 childDiagnostic() 无效? shouldn't it be the opposite?不应该是相反的吗? the parent and child don't need to communicate, but html is embedded.父母和孩子不需要沟通,但嵌入了html。 How do you fix this?你如何解决这个问题?

ng-content is not documented, but there are a lot of very simple examples that are quite misleading. ng-content没有记录在案,但有很多非常简单的例子非常具有误导性。

ng-content is projection target within component template, projected content itself belongs to template where it was declared and so are all template variables and methods. ng-content是组件模板中的投影目标,投影内容本身属于声明它的模板,所有模板变量和方法也是如此。

In your case root template is declared directly on html page, so its owner is Parent component (as the top most component), so all template vars are resolved against Parent component.在您的情况下,根模板直接在 html 页面上声明,因此其所有者是 Parent 组件(作为最顶层的组件),因此所有模板变量都针对 Parent 组件进行解析。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM