2015-10-15 81 views
17

请帮助你吗?刚开始使用Angular 2并遇到以下问题。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

它看起来简单但我错过了一些东西。我试图实现的是将应用程序外部的值传递给它。

谢谢。

+0

。尝试将'mynumber'传递给子组件,它应该可以工作。 –

+0

嗨。感谢您的回复,但我试图将外部角度的值传递给它。不知道如何?干杯 – BoomBoomBoom

回答

9

您无法为应用程序的根组件指定属性绑定(输入)。如果你真的想为它指定一些绑定,你应该使用额外的组件。见this plunkers

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 {} 
+1

很酷。谢谢。我想我在问不可能的事情。我希望在主html页面中提供来自其他控件等的一些数据。谢谢您的帮助 – BoomBoomBoom

5

一种解决方法是阅读它直接使用ElementRef

constructor(elementRef:ElementRef) { 
    console.log(elementRef.nativeElement.getAttribute('someattribute'); 
} 

,并使用ElementRef使用它像也

<myapp mynumber='41'></myapp> 

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

4

更新到答案:使用渲染。改为selectRootElement。 任何试图使用ElementRef.nativeElement的人都可能会看到各种有关这是最后手段的警告等。这里是一个修改后的更安全的版本。

constructor(renderer: Renderer){ 
    let rootElement = renderer.selectRootElement('app-root'); 
    this.whateverInput = rootElement.getAttribute('my-attribute'); 
} 
2

对于使用那些角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