繁体   English   中英

我可以使用 Angular 环境变量来动态更改 HTML 吗?

[英]Can I use Angular environment variables to dynamically alter HTML?

我有一个 Angular 应用程序,它有一个显示一系列选项卡的 header 导航栏,但我想根据应用程序构建的环境动态更改显示哪些选项卡。

header 组件 HTML

<nav id="nav"
    <ul class="navbar-nav mr-auto" role="tablist">
      <ng-container *ngFor="let app of appList">
        <li role="presentation"
            class='nav-item'>
          <a class="nav-link"
              (click)="selectApp(app.id)">
            {{app.name}}
          </a>
      </li>
      </ng-container>
    </ul>
  </div>
</nav>

这些选项卡绑定到组件的 TS 文件中的 object appList

export class HeaderComponent implements OnInit {

  appSelected: string;
  appList = [
    {
      'id': 0,
      'name': 'Home',
      'routerLink': '/'
    },
    {
      'id': 1,
      'name': 'Story Pointing',
      'routerLink': '/spe'
    },
    {
      'id': 2,
      'name': 'T-shirt Sizing',
      'routerLink': '/tse'
    },
    {
      'id': 3,
      'name': 'Asset Tracker',
      'routerLink': '/tat'
    }
  ]

  constructor() { }

  ngOnInit(): void {
    this.appSelected = this.appList[0].name
  }

  selectApp(appId:any){
    this.appSelected = this.appList[appId].name
  }

目前,我有两个环境:本地和开发。 当我在本地环境中构建应用程序时,我希望所有 4 个选项卡都显示在导航栏中。 但是,当我在服务器环境中构建应用程序时,我只想在导航栏上显示appList object 的前三个条目。

我尝试使用appList object 的修改版本向每个环境变量添加自定义tabList属性; 但是,当我在将环境变量导入我的组件后尝试引用它时,它不会显示为变量的属性。

环境.local.ts

export const environment = {
  production: false,
  apiUrl: "http://localhost:8080/",
  tabList: [
    {
      'id': 0,
      'name': 'Home',
      'routerLink': '/'
    },
    {
      'id': 1,
      'name': 'Story Pointing',
      'routerLink': '/spe'
    },
    {
      'id': 2,
      'name': 'T-shirt Sizing',
      'routerLink': '/tse'
    },
    {
      'id': 3,
      'name': 'Asset Tracker',
      'routerLink': '/tat'
    }
  ]
}

我是否需要使用另一种技术来获得上述效果,或者有没有办法使用环境变量来实现?

在环境文件中声明变量时,应在所有环境文件中声明相同的变量。

这是我的建议:

环境.common.ts

export const commonEnvironment = {
  tabs: [ /* your tabs here */ ]
};

其他环境文件

import { commonEnvironment } from './environment.common';

export const environment = {
  ...commonEnvironment,
  tabs: commonEnvironment.tabs.slice(0, 4) // Adapt the "4" to your environment
};

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM