首页 > 解决方案 > 切换打字稿界面的多个值

问题描述

我在 Angular 12 中有一个带有几个图标的操作栏。当用户单击其中一个时,会打开一个新的部门/面板。现在,当单击一个图标时,只有该面板必须打开,而其他面板则关闭。我创建了一个界面来设置哪个面板处于活动状态。

export interface PanelModel{
  apps : boolean;
  payroll: boolean;
  chat : boolean;
  mycloud: boolean;
}

在我的服务中,我已经初始化了接口

public chosen: PanelModel = {
   apps:false,
   payroll:false,
   chat:false,
   mycloud:false
};

现在,如果单击应用程序图标,我想设置 this.chose.apps = true,然后将 payroll、chat、mycloud 变量设置为 false。

如何设置接口的值?

标签: angulartypescript

解决方案


如果我对您的理解正确,您希望遍历键并将所选图标动态设置为 true,将其余图标设置为 false,因此如果是这种情况,那么下面的内容应该可以解决您的问题。

// Your interface.
interface PanelModel{
  [apps: string]: boolean;
  payroll: boolean;
  chat : boolean;
  mycloud: boolean;
};

// Object that implements your interface with default values.
const chosen: PanelModel = {
 apps: false,
 payroll: false,
 chat : false,
 mycloud: false
};

// Your clicked icon (as an example).
const clickedIcon = 'apps'

// Log what it looks like before.
console.log('BEFORE: ', chosen);

// Iterate through the keys to find the one to set to true and set rest to false.
Object.keys(chosen).map(key => {
    if(key === clickedIcon) {
        chosen[key] = true;
    } else {
        chosen[key] = false;
    }
});

// Below is doing the same as above but in a single line of code.
// Object.keys(chosen).map(key => key === clickedIcon? chosen[key] = true : chosen[key] = false);

// Log output.
console.log('AFTER: ', chosen);

由于您特别提到了 Angular 12,您可以将按钮单击挂钩到一个函数,该函数将 $event(图标名称或其他)传递给专门执行此迭代的方法。(假设您动态渲染按钮,那么您可以直接传递名称而不是事件)

// Method in your typescript component file
  onIconClick(tabName: string): void {

    Object.keys(chosen).map(key => {
      if(key === tabName) {
        chosen[key] = true;
      } else {
        chosen[key] = false;
      }
    });
  }

// Your HTML component file (if buttons a rendered dynamically)
<div *ngFor="let tab of tabs">
  <button type="button" class="button (click)="onIconClick(tab)">{{tab}}</button>
</div>

这是Typescript Playground 中的一个示例


推荐阅读