angular - 如何在 Angular 2 中绑定(bind) HTML 中组件的静态变量?

标签 angular typescript angular2-services

我想在 HTML 页面中使用组件的静态变量。 如何将组件的静态变量与 Angular 2 中的 HTML 元素绑定(bind)?

import { Component, OnInit } from '@angular/core';
import { Observable } from 'rxjs/Rx';
@Component({
  moduleId: module.id,
  selector: 'url',
  templateUrl: 'url.component.html',
  styleUrls: ['url.component.css']
})
export class UrlComponent {

  static urlArray;
  constructor() {
  UrlComponent.urlArray=" Inside Contructor"
  }
}
<div>
  url works!
   {{urlArray}}
</div >

最佳答案

组件模板中绑定(bind)表达式的范围是组件类实例。

您不能直接引用全局变量或静态变量。

作为解决方法,您可以向组件类添加一个 getter

export class UrlComponent {

  static urlArray;
  constructor() {
    UrlComponent.urlArray = "Inside Contructor";
  }

  get staticUrlArray() {
    return UrlComponent.urlArray;
  }

}

并像这样使用它:

<div>
  url works! {{staticUrlArray}}
</div>

关于angular - 如何在 Angular 2 中绑定(bind) HTML 中组件的静态变量?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39193538/

相关文章:

c# - ASP.NET Core SignalR 使用 Azure AD 返回 401 Unauthorized

javascript - 类型错误 : Cannot read property 'then' of undefined for global variables

javascript - 无法访问 Angular 2 组件中 addEventListener() 中的 'this' 上下文

angular - 重定向到 Angular 中的上一页

angular - Angular 2 中服务的单个实例

angular - 理解@input——从 parent 到 child

node.js - undefined 不可迭代(无法读取属性 Symbol(Symbol.iterator))

angular - AngularJS 2 中的 InterpolateProvider

typescript - 为给定类型键入合并函数的集合

javascript - typescript 中可以映射函数类型吗?