网站搜索

angular - Angular2 模板 - 使用不在此上的变量


在 Angular 2 模板中使用不在 this 上下文中的变量是否可能?

例如:

<div>{{ fooBar }}</div>

fooBar 需要在这个组件使用的类中某处定义,例如:

export class MyComponent {
  public fooBar: boolean = true;
}

但是如果你只是想使用一个不在类中的值呢?例如,也许你想导入一个字符串常量列表,并在模板中有选择地显示它们:

import { MyService } from './my.service'; 
import { StringConstants } from '../string.constants';

@Component({
  selector: 'my-component',
  template: `
    <div *ngIf="isPrimary">{{ StringConstants.PRIMARY }}</div>
    <div *ngIf="isSecondary">{{ StringConstants.SECONDARY }}</div>
  `
})

export class MyComponent {
  public isPrimary: boolean;
  public isSecondary: boolean;

  constructor (private myService: MyService) {
    this.isPrimary = myService.getPrimaryContext();
    this.isSecondary = myService.getSecondaryContext();
  }
};

答案#1

我看到有两种方式可以实现它:

1) 在组件中定义与您的常量同名的变量

export class MyComponent {
  StringConstants = StringConstants;
  ...

2) 使用 ES6 字符串插值

template:`
  <div *ngIf="isPrimary">${StringConstants.PRIMARY}</div>
  <div *ngIf="isSecondary">${StringConstants.SECONDARY}</div>
`
export class MyComponent {