2016-10-26 85 views
0

我試圖通過ES6獲得angular2的保留,沒有打字稿。問題是我不知道如何渲染一個子組件。我有這個基礎組件,只是拿着應用程序。在那個組件中,我希望能夠渲染,比如頭部組件和頁腳組件。現在只有我的基礎組件被渲染。Angular2 + Es6。渲染子組件

我該怎麼做?

這裏是我的代碼:

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}; 
+0

我還沒有得到這個權利。任何人有解決方案? – user2952238

+0

你可以將你的代碼添加到github倉庫或者倉庫中,這樣我們可以幫你嗎? –

回答

2

我認爲問題在於如何定義選擇器和模板。

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

我希望這有助於。

+0

嘿,非常感謝答案,事情變得更加清晰。現在,所有三個元素都被渲染(應用程序,頁眉,頁腳)。但是頁眉和頁腳是空的。我如何添加一些內容給他們? – user2952238

+0

我想從它們的相應文件中獲得。就像你上面看到的,我想從'app.header.js'填充'

'。 – user2952238

+0

這就是應該發生的事情。只需將內容添加到您的app.header模板。但是,您可能想要選擇不同的選擇器。因爲'header'和'footer'是合法的HTML標籤,所以'app-header'可能代替'header'和'app-footer'而不是'footer'。我會改變我的答案來反映這一點。 –