如何在angular 2 中绑定HTML 中组件的静态变量?

How to bind static variable of component in HTML in angular 2?

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

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 >

组件模板中绑定表达式的范围是组件class实例。

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

作为解决方法,您可以将 getter 添加到您的组件 class

export class UrlComponent {

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

  get staticUrlArray() {
    return UrlComponent.urlArray;
  }

}

并像这样使用它:

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

为避免Angular在每个循环中调用get staticUrlArray,您可以在组件的public范围内保存一个class引用:

export class UrlComponent {

  static urlArray;

  public classReference = UrlComponent;

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

}

然后就可以直接使用了:

<div>
  url works! {{ classReference.urlArray }}
</div>

您也可以只声明一个 class 类型的字段,例如:

export class UrlComponent {
  static urlArray;

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

然后您可以使用此前缀引用静态变量:

<div>
  url works! {{UrlComponent.urlArray}}
</div>

这对于直接在您的模板中引用诸如枚举之类的东西或诸如控制台之类的对象也是必要的。

有趣的是,在模板中使用以“readonly”为前缀的 class-attribute 确实有效。因此,如果您的静态变量实际上是一个常量,请继续使用

export class UrlComponent {
    readonly urlArray;
}

在构造函数中不编码的解决方案:

export class UrlComponent {

  static readonly urlArray = 'Inside Class';

  readonly UrlArray = UrlComponent.urlArray;

  constructor() {  }
}

您可以在其他组件中使用该静态字段或 类:

import {UrlComponent} from 'some-path';
export class UrlComponent2 {
  readonly UrlArray = UrlComponent.urlArray;
}

在模板中使用(注意 UrlArray 中的大写 'U'):

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

这对我有用,但验证器的错误消息停止工作

这是我的代码。

<form [formGroup]="staticformGroup" class="form">
    <div class="box">
        <input type="text" id="uname" class="field" formControlName="name">
         <span class="PlaceHolder" id="namePlaceHolder">Name</span>
         <small *ngIf="name.invalid && name.touched" class="text-danger">Name is Required</small> 
    </div>
    <div class="box">
         <input type="mailOrNum" id="mailOrNum" class="field" formControlName="email">
         <span class="PlaceHolder" id="mailPlaceHolder">Email</span>
         <small *ngIf="email.invalid && email.touched" class="text-danger">invalid value</small>
    </div>
</form>

ts 文件:

static signup = new FormGroup({
    'name': new FormControl("", Validators.required),
    'email': new FormControl("", [Validators.required, Validators.email])
});

get staticformGroup():FormGroup{
    return SignUpFormComponent.signup;
}