Angular 2外部输入

  • 本文关键字:外部 Angular angular
  • 更新时间 :
  • 英文 :


你能帮忙吗?从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

看起来很简单,但我错过了一些东西。我想要实现的是传递一个值从外面的应用程序进入它。

谢谢。

您不能为应用程序的根组件指定属性绑定(输入)。如果你真的想为它指定一些绑定,你应该使用额外的组件。看这个活塞

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>

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

使用ElementRef: use 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>

你可以像这样使用@Attribute注释:

class Component {
    constructor(@Attribute('attributeName') public param:String){
        /** some process with your injected param **/
    }
}

在我的应用中测试并成功运行。

找到了路:https://gillespie59.github.io/2015/10/08/angular2-attribute-decorator.html

最新更新