如何在 angular 2 中绑定 HTML 中组件的静态变量? [英] How to bind static variable of component in HTML in angular 2?

查看:29
本文介绍了如何在 angular 2 中绑定 HTML 中组件的静态变量?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在 HTML 页面中使用一个组件的静态变量.如何将组件的静态变量与 angular 2 中的 HTML 元素绑定?

import { Component, OnInit } from '@angular/core';从 'rxjs/Rx' 导入 { Observable };@成分({模块 ID:module.id,选择器:'网址',templateUrl: 'url.component.html',styleUrls: ['url.component.css']})导出类 UrlComponent {静态 urlArray;构造函数(){UrlComponent.urlArray="内部构造函数"}}

网址有效!{{urlArray}}</div >

解决方案

组件模板中绑定表达式的作用域是组件类实例.

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

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

导出类 UrlComponent {静态 urlArray;构造函数(){UrlComponent.urlArray = "内部构造函数";}获取 staticUrlArray() {返回 UrlComponent.urlArray;}}

并像这样使用它:

网址有效!{{staticUrlArray}}

I want to use a static variable of a component in HTML page. How to bind static variable of component with a HTML element in angular 2?

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 >

解决方案

The scope of binding expressions in a components template is the components class instance.

You can't refer to globals or statics directly.

As a workaround you can add a getter to your components class

export class UrlComponent {

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

  get staticUrlArray() {
    return UrlComponent.urlArray;
  }

}

and use it like:

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

这篇关于如何在 angular 2 中绑定 HTML 中组件的静态变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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