2016-03-28 9 views
2

何らかの理由で、ngOnInit()メソッドから試してもプロパティの@Input値にアクセスできません。ngOnInitで@Inputが定義されていません2

index.htmlを

<html> 
    <head> 
    <title>Angular 2 QuickStart</title> 
    <meta name="viewport" content="width=device-width, initial-scale=1">  

    <!-- 1. Load libraries --> 
    <!-- IE required polyfills, in this exact order --> 
    <script src="node_modules/es6-shim/es6-shim.min.js"></script> 
    <script src="node_modules/systemjs/dist/system-polyfills.js"></script> 
    <script src="node_modules/angular2/es6/dev/src/testing/shims_for_IE.js"></script> 

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

    <!-- 2. Configure SystemJS --> 
    <script> 
     System.config({ 
     packages: {   
      app: { 
      format: 'register', 
      defaultExtension: 'js' 
      } 
     } 
     }); 
     System.import('app/main') 
      .then(null, console.error.bind(console)); 
    </script> 
    </head> 

    <!-- 3. Display the application --> 
    <body> 
    <my-app title="Quick start guide">Loading...</my-app> 
    </body> 
</html> 

main.ts は常に定義されていないと、テンプレート<h1>{{ title }}</h1>は空の値をレンダリングしていることを

import { bootstrap } from 'angular2/platform/browser'; 
import { AppComponent } from './app.component'; 

bootstrap(AppComponent); 

app.component.ts

import {Component, Input, OnInit} from 'angular2/core' 

@Component({ 
    selector: 'my-app', 
    template: '<h1>{{ title }}</h1>' 
}) 
export class AppComponent { 
    @Input() title: string; 

    constructor() { 
    } 

    ngOnInit() { 
     console.log(this.title); 
    } 
} 

私が紛失していることはありますか?私はこれを数回前に行い、それはいつも働いていました。

答えて

4

@Input()は、ルートコンポーネントでサポートされていません。

命令的属性を読み取るためにElementRefを使用して解決策:

class AppComponent { 
    constructor(elm: ElementRef) { 
     this.title = elm.nativeElement.getAttribute('title'); 
    } 
} 

入力のみの角度成分のテンプレートに追加されたコンポーネントまたはディレクティブのために初期化されます。 <body>要素は角度コンポーネントではありません。

は、ルートコンポーネントを使用して追加されるため、この問題は、関連するhttps://github.com/angular/angular/issues/6370かもしれないもhttps://github.com/angular/angular/issues/1858

を参照してくださいDynamicComponentLoader.loadAsRoot()

0

入力は、アプリケーションのルートコンポーネント(アプリケーションのブートストラップ時に指定したもの)で使用することはできません。それはサポートされていません。

コンポーネントの注入されたComponentRefからnativeElement(およびそのgetAttributeメソッド)を使用して、独自の属性を参照する必要があります。そのような

何か:

@Component ({ ... }) 
export MyComponent { 
    constructor(compRef:ComponentRef) { 
    var someAttrValue = compRef.nativeElement.getAttribute('someAttr'); 
    } 
}