2016-03-28 82 views
2

由于某些原因,即使我尝试使用ngOnInit()方法,我也无法访问属性的@Input值。@Input在ngOnInit angular 2上未定义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

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); 
    } 
} 

这永远是不确定的和模板<h1>{{ title }}</h1>正在呈现一个空值。

我失踪了什么?我之前做过几次,它一直都很有效。

回答

4

@Input()不支持根组件。

使用ElementRef到势在必行读取属性一种解决方法:

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

输入仅初始化被添加到的角度成分的模板组件或指令。 <body>元素不是一个Angular组件。

https://github.com/angular/angular/issues/1858

看到这个问题也可能是相关https://github.com/angular/angular/issues/6370因为根组件使用添加DynamicComponentLoader.loadAsRoot()

0

输入不能用于应用程序的根组件(这是您在引导应用程序时提供的那个组件)。它不受支持。

您需要使用组件中注入的ComponentRef的nativeElement(及其getAttribute方法)引用属性。

类似的东西:

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