javascript - Angular - 如何使用一个函数来管理多个切换/点击事件?

标签 javascript angular typescript dom

请看附图。

所以,这是一个导航栏,点击任何选项卡,导航下方的内容将根据选择的选项卡而改变。

enter image description here

下面是一个示例代码,说明在单击 Bespoke Manufacturing 时处理单击事件时该函数如何工作:

 toggleBespoke() {
   this.showBespoke = true;
   this.showHow = false;
   this.showCasting = false;
   this.showForging = false;
   this.showInjection = false;
   this.showPressing = false;
   this.showTurning = false;
 }

如您所见,这很简单,将 about showAbout 变量设置为 true,而将所有其他变量手动设置为 false。

ngClass is used which gives the blue highlighted effect so only one of the tabs gets highlighted when selected as only one can be true whilst others are false.

然后将相同的逻辑应用于其他 6 个选项卡。

但这是我的问题,如何防止代码重复并仅在一个函数中处理此类点击事件?

最佳答案

您可以在组件中使用一个属性来存储事件选项卡。

export class AlarmsComponent {
  activeTab = 'bespoke';
}

然后你可以像这样在你的模板中使用它:

<ul class="tabs">
  <li>
    <a (click)="activeTab = 'bespoke'"
       [ngClass]="{active: activeTab === 'bespoke'}"
    >
      Bespoke manufacturing
    </a>
  </li>
  <li>
    <a (click)="activeTab = 'how'"
       [ngClass]="{active: activeTab === 'how'}"
    >
      How it works
    </a>
  </li>
</ul>

<div class="tab-bespoke" *ngIf="activeTab === 'bespoke'">
  Bespoke manufacturing tab content
</div>
<div class="tab-how" *ngIf="activeTab === 'how'">
  How it works tab content
</div>

关于javascript - Angular - 如何使用一个函数来管理多个切换/点击事件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63111816/

相关文章:

Angular 8 : Make FormBuilder Accept Numbers Only with Range for Latitude and Longitude

javascript - 在 DynamoDB 中搜索表失败时如何回调错误消息

php - 帮助创建一个可以连续播放音频文件的脚本,无论长度如何

typescript - 在 TypeScript 中,如何定义提供从成员对象返回的值的方法类型?

angular - 有没有办法向模板输入变量添加类型断言/注释?

angular - 如何在 Angular Material 4 中居中对齐卡片?

typescript - 没有 webpackJsonp 的 Webpack typescript 编译

javascript - 将 Div 移动到悬停的 Div 的 Y 位置(JQuery)

javascript - 新的 div 不接受文本值

css - 使用css将全局样式应用于material.angular mat-card设置背景色