Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.1k views
in Technique[技术] by (71.8m points)

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

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 >
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...