114

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 >

6 Answers 6

170

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>
Sign up to request clarification or add additional context in comments.

5 Comments

If HTML has for loop then ? I have loop which access the component static variable.. If I use "let person of persons()" it doesnt work. Here persons method return multiple person.. getting "TypeError: self.context.persons is not a function" error
@rajm Please create a new question with minimal code that allows to reproduce.
No, you most definitely do not need () on a getter, and shouldn't have it there. get staticUrlArray() {} is not public staticUrlArray() {} One is accessed directly like staticUrlArray, the other as a method like staticUrlArray().
See the below link also for reference.: github.com/angular/angular/issues/6429
55

To avoid Angular calling get staticUrlArray at each cycle, you can save a class reference in the public scope of the component:

export class UrlComponent {

  static urlArray;

  public classReference = UrlComponent;

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

}

And then you can use it directly:

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

2 Comments

For a simple variable I was using for the state of a checkbox, this method avoided dozens of calls to the get function. If used within a loop (e.g. rows of a table) that could really be detrimental. I'd say this is the better answer and the syntax is a bit simpler.
This is a very interesting solution. Declaring a reference to a class within the class itself seems kind of odd. But it does work in Angular.
7

You can also just declare a field of the class type, as such:

export class UrlComponent {
  static urlArray;

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

You can then reference static variables using this prefix:

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

This also works / is necessary to reference stuff like Enums or objects like console directly in your template.

2 Comments

seems very much like mithus7's answer
@BogdanD, indeed, with the small difference that I use "UrlComponent = UrlComponent" as I find this to be more expressive than using a generic "classReference" that doesn't show which class we're talking about. Also, I answered in March while mithus7 answered in April... Looking at it, I noticed that I had a typo in the template, fixed that...
1

this worked for me but the error msg for validators stopped working

this is my code.

<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 file:

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

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

Comments

0

Interestingly, consuming a class-attribute prefixed by "readonly" in the template DOES work. Therefore, if your static variable turns out to actually be a constant, go ahead and use

export class UrlComponent {
    readonly urlArray;
}

Comments

0

Solution without coding in constructor:

export class UrlComponent {

  static readonly urlArray = 'Inside Class';

  readonly UrlArray = UrlComponent.urlArray;

  constructor() {  }
}

you can use that static field in other components or classes:

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

using in template (note capital 'U' in UrlArray):

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

1 Comment

'static' modifier must precede 'readonly' modifier.ts(1029)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.