【问题标题】:Angular 2 external inputsAngular 2 外部输入
【发布时间】:2016-01-14 04:04:29
【问题描述】:

请问您能帮忙吗?刚从 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

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

谢谢。

【问题讨论】:

  • 这是在根组件中设置输入的问题。尝试在子组件中传递mynumber,它应该可以工作。
  • 嗨。感谢您的回复,但我正在尝试将外部角度的值传递给它。不知道怎么做?干杯

标签: angular


【解决方案1】:

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

【讨论】:

    【解决方案2】:

    使用 ElementRef 更新答案:改用 Renderer.selectRootElement。 任何尝试使用 ElementRef.nativeElement 的人都可能会看到各种警告,说明这是最后的手段等。这是一个经过修改的更安全的版本。

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

    【讨论】:

      【解决方案3】:

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

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

      并像使用它

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

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

      【讨论】:

        【解决方案4】:

        您不能为应用程序的根组件指定属性绑定(输入)。如果你真的想为它指定一些绑定,你应该使用额外的组件。见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 {}
        

        【讨论】:

        • 酷。谢谢。我想我在问不可能的事。我希望在主 html 页面上提供来自其他控件等的一些数据。感谢您的帮助
        猜你喜欢
        • 2017-06-21
        • 2017-04-21
        • 2017-02-27
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2016-09-02
        • 2023-03-04
        相关资源
        最近更新 更多