2016-01-06 62 views
3

我在使用Angular2呈現表達式時遇到問題。Angular2表達式不會呈現

例如,我有類似下面的例子,但{{profile.name}}什麼都不呈現。

但是,它不僅僅是從組件實例訪問某些東西的時候。無論我在表達中如何表達,它都不會呈現(例如{{1 + 2}})。並且,它會刪除表達式所包含的DOM元素的所有內容。

import { Component, View } from 'angular2/core' 

@Component({ 
    selector: 'my-component' 
}) 
@View({ 
    template: ` 
    <div class="user"> 
    {{profile.name}} 
    </div> 
    ` 
}) 
export class MyComponent { 
    profile 

    constructor() { 
    this.profile = { 
     name: 'John Smith' 
    } 
    } 
} 

不確定我錯過了什麼。任何幫助將非常感激!

編輯

所以我做了一些進一步的測試,並發現了問題,只有當我使用<router-outlet>發生。所以,我有東西,看起來像這個(道歉的代碼量)

app.ts

import { View, Component } from 'angular2/core' 
import { RouteConfig, RouterOutlet } from 'angular2/router' 

import { Home } from './home' 

@Component({ 
    selector: 'my-app' 
}) 
@View({ 
    template: '<router-outlet></router-outlet>', 
    directives: [RouterOutlet] 
}) 
@RouteConfig([ 
    { path: '/', redirectTo: ['/Home'] }, 
    { path: '/home', as: 'Home', component: Home } 
]) 
export class App { 
    constructor(public router: Router) {} 
} 

home.ts

import { Component, View } from 'angular2/core' 

@Component({ 
    selector: 'home', 
}) 
@View({ 
    template: '{{name}}' 
}) 
export class Home { 
    name:string = 'John Smith' 
} 
+1

您是否在使用它的父類中指定此組件?也就是說,它有'指令:[MyComponent]'? –

+0

任何錯誤消息?這是正確的孤立 – TGH

+0

我已經做了一些進一步的測試,並發現問題似乎只發生在我使用指令時。任何使用表達式加載的指令都會被刪除......我仍然難倒了。我會更新這個例子。 –

回答

1

我認爲標誌點的問題出在他的評論中!多開發一點。實際上,您需要明確定義要在另一個組件(除angular/core以外的組件)中使用的組件(和指令)到directives屬性中。

這裏是你會用你的MyComponent組件到另外一個方式:我與你MyComponent類測試這個

@Component({ 
    selector: 'my-app', 
    template: ` 
    <my-component></my-component> 
    `, 
    directives: [ MyComponent ] 
}) 
export class AppComponent { 
    (...) 
} 

和它的作品。

希望它可以幫助你, 蒂埃裏

+0

我做了一些進一步的測試,發現問題似乎只發生在我使用''指令時。任何使用表達式加載的指令都會被刪除......我仍然難倒了。我會更新這個例子。 –

1

這似乎是,如果你不包括zone.js.發生在引導之前添加import "zone.js/lib/browser/zone-microtask"; Angular爲我解決了這個問題。

+0

謝謝@xod這應該在angular.io教程中。 –

4

我有類似的問題。我有我的Angular2庫以錯誤的順序定義。

順序定義庫幫助:該系統polyfills的

<!-- Keep these first!!! --> 
<script src="~/node_modules/es6-shim/es6-shim.js"></script> 
<script src="~/node_modules/systemjs/dist/system-polyfills.js"></script> 

<script src="~/node_modules/angular2/bundles/angular2-polyfills.js"></script> 
<script src="~/node_modules/systemjs/dist/system.js"></script> 
... 

地點似乎是很重要的!

+0

聖潔的廢話!感謝這個答案!我真的很好奇你如何設法解決這個問題。 – Mono

+0

是的...我留下深刻的印象,你有這個。看起來Angular 2對於所有必須經過的「典禮」都有點脆弱 - 包括確保某些js文件按給定順序加載? – Catchops

1

我有一個類似的問題,使用路由器和路由器插座,只要我添加* ngFor或* ngIf-like語句就不會渲染我的頁面。 但是,鬍鬚表達式起作用。這是Angular v2.0.0-rc.6。

絕對沒有錯誤信息,只是一個空的頁面,這似乎很殘酷(是的,我在跟你說,Angular團隊;-))。

相對較新Angular2,我花了一段時間才能弄清楚,我錯過了CommonModule

import { CommonModule }  from "@angular/common"; 

@NgModule({ 
imports: [ 
    CommonModule, 
    yourRouting 
], 
declarations: [ 
    YourComponent 
] 
}) 

export class OrderModule { 
} 

我想通了通過去在Angular routing tutorial及其live demo和他們建立比較雷。

也許這可以幫助某人下線。

+0

感謝yuh bro ...這對我有幫助! –