【问题标题】:Can I use Angular environment variables to dynamically alter HTML?我可以使用 Angular 环境变量来动态改变 HTML 吗?
【发布时间】:2022-12-17 23:29:21
【问题描述】:

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

标头组件 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>

选项卡绑定到对象appList组件的TS文件.

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 对象的前三个条目。

我尝试使用 appList 对象的修改版本向每个环境变量添加自定义 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'
    }
  ]
}

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

【问题讨论】:

    标签: angular environment-variables


    【解决方案1】:

    当您在环境文件中声明一个变量时,您应该在所有环境文件中声明相同的变量。

    这是我的建议:

    环境.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
    };
    
    

    【讨论】:

      猜你喜欢
      • 2019-03-09
      • 1970-01-01
      • 2012-03-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-04-19
      • 1970-01-01
      • 2021-10-30
      相关资源
      最近更新 更多