Доступ к глобальной переменной из Angular шаблона - PullRequest
0 голосов
/ 13 марта 2020

Можно ли получить доступ к глобальной переменной из шаблона angular?

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

Затем в шаблоне HTML:

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

Можно ли получить 'cantAccess? 'чтобы быть верным в шаблоне?

Ответы [ 3 ]

0 голосов
/ 13 марта 2020

Объявите cantAccess как переменную publi c и попробуйте получить к ней доступ.

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>
0 голосов
/ 13 марта 2020

Да, вы можете получить доступ к глобальной переменной, но только переназначив ее на локальную. Вот как мы можем использовать типы Enum внутри шаблона

enum Status {
    Online,
    Offline
}

@Component({
    template: `{{Status.Online}}`
})
class Component {
    Status = Status;
}
0 голосов
/ 13 марта 2020

Вот обновленный фрагмент

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

Шаблон

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

Вот ссылка на фрагмент: https://stackblitz.com/edit/angular-xwwgrt

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...