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

6

112

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 >
Domoniquedomph answered 28/8, 2016 at 16:42 Comment(0)
E
168

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>
Elissaelita answered 28/8, 2016 at 16:45 Comment(5)
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" errorUndernourished
@rajm Please create a new question with minimal code that allows to reproduce.Zoltai
just posted .. #40173618Undernourished
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().Faiyum
See the below link also for reference.: github.com/angular/angular/issues/6429Tranquillize
S
53

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>
Sousaphone answered 27/4, 2018 at 10:5 Comment(2)
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.Qr
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.Summerlin
L
5

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.

Levitan answered 9/3, 2020 at 14:18 Comment(2)
seems very much like mithus7's answerHartley
@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...Levitan
L
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;
}
Lazar answered 10/4, 2021 at 13:16 Comment(0)
W
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;
}
Whoosh answered 21/9, 2020 at 9:23 Comment(0)
R
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>
Retch answered 23/10, 2020 at 12:36 Comment(1)
'static' modifier must precede 'readonly' modifier.ts(1029)Haiti

© 2022 - 2024 — McMap. All rights reserved.