Angular 2 输入绑定(bind)不起作用

标签 angular

<分区>

index.html:

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

应用程序组件.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 文件中获取变量以将其发送到组件?

最佳答案

更新

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');
  }
}

此外,如果你想将数据作为对象传递,你可以看看这个问题


原创

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

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

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

关于Angular 2 输入绑定(bind)不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39614451/

相关文章:

javascript - 带有重定向的 Angular 2 AuthGuard 服务?

angular - 在 Angular 2 应用程序中导入 socket.io-client 时出错

当基本 href 不是 root 时,Angular 2 默认路由

css - 如何为 Angular Material 分页器自定义 css?

Angular Material 2 DatePicker,动态改变显示格式

尝试为 RouterOutlet 和 NgIf 配置 _source 的 Angular 和错误

angular - ViewContainerRef.clear() 是否从内存中删除组件?

javascript - Angular 4 : handle browser refresh/close event

angular - 共享嵌套的 Angular 2/4 服务

angular - 第一次加载页面时调用 ngOnDestroy