javascript - Angular2 + Es6。渲染子组件

标签 javascript angular ecmascript-6

我正在尝试使用 ES6 来掌握 angular2,而不是使用 TypeScript。问题是我不知道如何渲染子组件。我有这个基本组件,它只包含应用程序。在该组件中,我希望还能够渲染页眉组件和页脚组件。现在只有我的基本组件被渲染。

我该怎么做?

这是我的代码:

HTML:

<!DOCTYPE html>
<html lang="en">
<head>
</head>
<body>
    <application>
        <header></header>
    </application>

    <script src="/node_modules/zone.js/dist/zone.js"></script>
    <script src="/node_modules/reflect-metadata/Reflect.js"></script>
    <script src="/dist/js/app.js"></script>

</body>

app.js

import {Component} from 'angular2/core';
import {bootstrap} from 'angular2/platform/browser';
import {Header} from './components/app.header';

class Base {
    static get annotations() {
        return [
            new Component({
                selector: "body",
                template: '<application>base</application>'
            }),
        ];
    }

    constructor () {}
}

export {Base};

bootstrap(Base);

app.header.js

import {Component} from 'angular2/core';

class Header {
    static get annotations() {
        return [
            new Component({
                selector: 'header',
                template: '<h1>header</h1>'
            }),
        ];
    }

    constructor () {}
}

export {Header};

最佳答案

我认为问题在于您如何定义选择器和模板。

在index.html

更改:

<body>
    <application>
        <header></header>
    </application>

进入:

<body>
    <application></application>

在 app.js 中

new Component({
    selector: "application",
    template: '<app-header></app-header>'
}),

然后您可以更改 app.js 模板以包含页脚:

new Component({
    selector: "application",
    template: '<app-header></app-header><app-footer></app-footer>'
}),

您通常不希望标签之间有任何内容:

<application>Nothing goes here</application>
<app-header>Nothing goes here</app-header>
<app-footer>Nothing goes here</app-footer>

除非这些是行为类似于 *ngIf*ngFor 的“结构指令”。这是文档:

https://angular.io/docs/ts/latest/guide/structural-directives.html

我希望这会有所帮助。

关于javascript - Angular2 + Es6。渲染子组件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40263146/

相关文章:

javascript - 对 Javascript 层次结构行为感到困惑(给出示例代码)

javascript - @angular/pwa service worker 没有在我已经存在的项目上工作

javascript - 无法使用 Sinon 在导入的文件中 stub 函数调用

javascript - 为什么箭头函数没有参数数组?

javascript - 使用 ID 从 Google 表格中查找正确的值 - 避免多个 "else if" block - 构建数组

javascript - 使用依赖注入(inject)在javascript中返回一个函数

angular - 如何在 typescript 构造函数中将数组对象转换为字符串?

javascript - 获取未旋转的旋转矩形的边界

javascript - Angular 可编辑选择未保存

typescript - 如何在服务中注入(inject)Document?