0

Is it possible to access a global variable from an angular template?

let cantAccess = false;

@Component({
  selector: 'app-payment',
  templateUrl: './buy.component.html',
  styleUrls: ['./buy.component.scss']
})

export class BuyComponent implements OnInit, AfterViewInit {


  constructor() {
  }

  ngOnInit() {
    cantAccess = false;
  }
}

Then in template HTML:

<section>
  //Can't read this variable
  {{ cantAccess }}
</section>

Is it possible to get 'cantAccess' to appear true in the template?

georgeawg
  • 48,608
  • 13
  • 72
  • 95
Hayden
  • 43
  • 3
  • 9
  • Does this answer your question? [How can I declare a global variable in Angular 2 / Typescript?](https://stackoverflow.com/questions/36158848/how-can-i-declare-a-global-variable-in-angular-2-typescript) – PHP Ninja Mar 13 '20 at 04:25
  • The answer is no. Templates only have access to component scoped variables. – bryan60 Mar 13 '20 at 04:30

3 Answers3

0

Here is updated snippet

import { Component } from '@angular/core';

@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: [ './app.component.css' ]
})
export class AppComponent  {
  @Input() cantAccess = false;
  constructor() {
  }
  ngOnInit() {
    this.cantAccess = true;
  }
}

Template

<section>
  //Can't read this variable
  {{ cantAccess }}
</section>

Here is snippet link: https://stackblitz.com/edit/angular-xwwgrt

PHP Ninja
  • 1,055
  • 2
  • 9
  • 28
0

Declare cantAccess as public variable and try accessing it.

import { Component } from '@angular/core';

    @Component({
      selector: 'my-app',
      templateUrl: './app.component.html',
      styleUrls: [ './app.component.css' ]
    })
    export class AppComponent  {
      public cantAccess = false;
      constructor() {
      }
      ngOnInit() {
      }
    }

    <section>
      //Can't read this variable
      {{ cantAccess }}
    </section>
Vishnu Shenoy
  • 862
  • 5
  • 18
0

Yes you can access global variable, but only by reassigning it to a local one. This is how we can use Enum types inside a template

enum Status {
    Online,
    Offline
}

@Component({
    template: `{{Status.Online}}`
})
class Component {
    Status = Status;
}
Humberd
  • 2,794
  • 3
  • 20
  • 37