Angular 2输入绑定不起作用 [英] Angular 2 Input binding does not work

查看:86
本文介绍了Angular 2输入绑定不起作用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

index.html:

index.html:

  <app [myname]="some_name"></app>

app.component.ts:

app.component.ts:

  import {Component, Input, Output} from '@angular/core';

  @Component({
    selector: 'app',
    template: '<span>{{myname}}</span>'
  })

  export class CupBuyComponent {
      @Input() myname: String;

      constructor(){
          console.log(this.myname);
      }
  }

JS控制台显示未定义.如何从.html文件中获取变量以将其发送到组件?

JS console says undefined. How can I get variables from .html file to send it to component?

推荐答案

更新

此方法不起作用的原因是您的index.html其中 你放置的不是一个角度 成分.因此,Angular将不会编译此元素.和 Angular在运行时不读取属性值,仅在 编译时,否则会导致性能下降.

The reason why this is not working is that your index.html in which you place the is not an angular component. Because of this, Angular won't compile this element. And Angular does not read attribute values during runtime, only during compile time, as otherwise we would get a performance hit.

https://github.com/angular/angular/issues/1858# issuecomment-151326461

这将满足您的要求:

index.html

<app myname="some_name"></app>

根组件

export class CupBuyComponent {
  @Input() myname: String;

  constructor(elm: ElementRef){
    this.myname = elm.nativeElement.getAttribute('myname');
  }
}

此外,如果您希望将数据作为对象传递,则可以查看此问题

Also if you want pass data as object you can take a look at this question

原始

如果您想将数据作为文本传递,那么应该是

If you want to pass data as text then it should be

<app [myname]="'some_name'"></app>

<app myname="some_name"></app>

这篇关于Angular 2输入绑定不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆