@Input 在 ngOnInit 角度 2 上未定义

nic*_*nli 2 javascript angular

由于某种原因,即使我尝试使用 ngOnInit() 方法,我也无法访问属性的 @Input 值。

索引.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>
Run Code Online (Sandbox Code Playgroud)

主要.ts

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

bootstrap(AppComponent);
Run Code Online (Sandbox Code Playgroud)

应用程序组件.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);
    }
}
Run Code Online (Sandbox Code Playgroud)

console.log(this.title)始终是未定义的,并且模板<h1>{{ title }}</h1>呈现空值。

我缺少什么?我之前这样做过几次,而且总是有效。

Gün*_*uer 5

@Input()根组件不支持。

使用命令式ElementRef读取属性的解决方法:

class AppComponent {
    constructor(elm: ElementRef) {
        this.title = elm.nativeElement.getAttribute('title'); 
    }
}
Run Code Online (Sandbox Code Playgroud)

仅针对添加到 Angular 组件模板的组件或指令初始化输入。该<body>元素不是 Angular 组件。

另请参阅https://github.com/angular/angular/issues/1858

此问题也可能与https://github.com/angular/angular/issues/6370相关,因为根组件是使用添加的DynamicComponentLoader.loadAsRoot()