2015-06-05 27 views
1

我聲明瞭一個選擇「應用程序」組件 然後我用它像後續Angular 2 alpha 22,如何通過屬性傳遞值到組件?在我寫這個模板</p> <pre><code><app title="Awesome Title"></app> </code></pre> <p>:</p> <pre><code>The title passed {{ title }} </code></pre> <p>我沒加寫組件註釋:

@Component({ 
    selector: 'app', 
    properties: {title:'title'} // also tried ['title'] 
}); 

但沒有顯示出來,輸出

The title passed 

任何幫助?謝謝

回答

2

由於某種原因,properties似乎無法在引導的根應用上工作。

嘗試創建一個名爲'title-app'的組件並將其加載到'app'中。

// inner component 
@Component({ 
    selector: 'title-component', 
    properties: {title:'title'} 
}) 
@View({ template: '<h1>{{title}}</h1>'}) 
class titleComponent{} 

// root app 
@Component({ selector: 'app' }) 
@View({ 
    directives: titleComponent, 
    template: '<title-component [title]="Some Title"></title-component>' 
}) 
class App{} 

您可能還想使用最新版本的Angular2:目前alpha-26。從alpha-26 +開始,如果你的財產是同一個名字,你可以只稱它一次。

properties: {'title': 'title'} =>properties: 'title'

+0

如果您需要使用根應用程序(例如,因爲您從靜態HTML傳遞屬性),您仍然可以。但您必須使用ElementRef: https://github.com/angular/angular/issues/1858#issuecomment-137696843 – filiph

+0

屬性的語法已更改爲['title:title'] – vangorra

2

做到這一點,正確的做法是:

import { 
    ComponentAnnotation as Component, 
    ViewAnnotation as View, bootstrap 
} from 'angular2/angular2'; 
import {Attribute} from 'angular2/src/core/annotations_impl/di'; 


@Component({ 
    selector: 'app' 
}) 
@View({ 
    template: '{{goofy}} stuff' 
}) 
class App { 
    goofy:string; 
    constructor(@Attribute('goofy') goofy:string) { 
     this.goofy = goofy; 
    } 
} 

bootstrap(App); 

查看完整Plunker這裏http://plnkr.co/edit/n2XWez69HNJbixH3tEmR?p=preview

然而,這是目前打破,是一個已知的問題https://github.com/angular/angular/issues/1858

+0

我想使用兩個在這種情況下,@Attribute屬性讓我們假設愚蠢和低調。但這不適合我。有沒有解決辦法。我正在使用角阿爾法42.屬性工作正常的一個屬性。 –

+0

看起來像導入現在是來自「angular2/core」'的import {Attribute}。我使用的是alpha 47。 – mikebridge

3

在撰寫本文時,最新版本是alpha.26。 屬性定義略有改變,所以這裏是新的語法

@Component({ 
    selector: 'app', 
    properties: ['title:title'] 
}); 

<div [title]="Some Title"></div> 

我已經開始了一系列博客文章的演示角2點的概念。看看這裏:

http://www.syntaxsuccess.com/viewarticle/angular-2.0-examples

我對如何通過屬性分配屬性組件的工作示例。查看樹視圖示例,因爲它大量使用它。

相關問題