angular2个外部input
请你帮忙吗? 刚开始Angular 2,有以下问题。
我的组件如下:
@Component({ selector: 'myapp', inputs: ['mynumber'] }) @View({ template: `<p>The next number is {{ mynumber + 1 }}</p>' }) export class App { mynumber: number; } bootstrap(App); 在我的HTML里面:
 <myapp [mynumber]='41'></myapp> 
但是运行时,我得到以下内容:
 下一个号码是NaN 
它看起来很简单,但我错过了一些东西。 我想要实现的是将应用程序外部的值传递给它。
谢谢。
您不能为应用程序的根组件指定属性绑定(input)。 如果你真的想为它指定一些绑定,你应该使用额外的组件。 看到这个强盗 。
 import {Component, Input} from 'angular2/angular2' @Component({ selector: 'myapp', template: ` <p>The next number is {{ mynumber + 1 }}</p> ` }) class App { @Input() mynumber: number; } @Component({ selector: 'root', directives: [App], template: ` <myapp [mynumber]="41"></myapp> ` }) export class Root {} 
 解决方法是直接使用ElementRef读取它: 
 constructor(elementRef:ElementRef) { console.log(elementRef.nativeElement.getAttribute('someattribute'); } 
并使用它
 <myapp mynumber='41'></myapp> 
使用ElementRef更新答案:改为使用Renderer.selectRootElement。 任何人尝试使用ElementRef.nativeElement可能会看到各种警告如何这是最后的手段等这里是一个修改,更安全的版本。
 constructor( renderer: Renderer ){ let rootElement = renderer.selectRootElement('app-root'); this.whateverInput = rootElement.getAttribute('my-attribute'); } 
对于那些使用angular度4:如果你决定使用它作为一个像这样的属性
  <myapp mynumber='41'></myapp> 
你可以像这样使用annotation @Attribute:
 class Component { constructor(@Attribute('attributeName') public param:String){ /** some process with your injected param **/ } } 
testing并在我的应用程序成功工作。
find方法: https : //gillespie59.github.io/2015/10/08/angular2-attribute-decorator.html