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

新手上路,请多包涵

我想在 HTML 页面中使用组件的静态变量。如何将组件的静态变量与角度 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 >

原文由 Santosh Hegde 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 1.1k
2 个回答

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

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

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

export class UrlComponent {

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

  get staticUrlArray() {
    return UrlComponent.urlArray;
  }

}

并像这样使用它:

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

原文由 Günter Zöchbauer 发布,翻译遵循 CC BY-SA 3.0 许可协议

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

这是我的代码。

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

原文由 Rajini Nirmal 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进