You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Angular 4实现菜单点击后为指定section添加/切换active类

Convert jQuery Language Menu Interaction to Angular 4

Let's ditch the jQuery DOM manipulation and implement this the proper Angular 4 way—using data binding and component logic instead of direct element selection. Here's a clean, maintainable solution:

Step 1: Component Template (HTML)

First, update your template to use Angular's event binding and ngClass for dynamic class updates:

<ul>
  <li (click)="setActiveLang('english')">English</li>
  <li (click)="setActiveLang('hindi')">Hindi</li>
  <!-- Add more language options here if needed -->
</ul>

<section id="english" class="lang" [ngClass]="{'active': activeLang === 'english'}">
  <!-- Your English content goes here -->
</section>

<section id="hindi" class="lang" [ngClass]="{'active': activeLang === 'hindi'}">
  <!-- Your Hindi content goes here -->
</section>

Step 2: Component Class (TypeScript)

Next, add the logic to track the active language in your component class:

import { Component } from '@angular/core';

@Component({
  selector: 'app-language-switcher',
  templateUrl: './language-switcher.component.html',
  styleUrls: ['./language-switcher.component.css']
})
export class LanguageSwitcherComponent {
  // Set default active language (we'll use English here)
  activeLang: string = 'english';

  setActiveLang(lang: string): void {
    // Simply update the active language variable
    this.activeLang = lang;
    // No need to manually remove classes—Angular handles that automatically!
  }
}

Step 3: CSS Styling

Add your styling to control visibility based on the active class:

.lang {
  display: none;
}

.lang.active {
  display: block;
}

How This Works

Instead of querying the DOM like jQuery does, we're using Angular's data binding:

  • When you click a menu item, the setActiveLang method updates the activeLang property.
  • The ngClass directive on each section checks if activeLang matches its language ID. If it does, the active class is added; if not, it's removed automatically.

This approach is more aligned with Angular's component-based architecture, easier to test, and avoids the pitfalls of direct DOM manipulation in a framework designed to handle view updates via data.

内容的提问来源于stack exchange,提问作者Jafaruddeen Ansari

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.25 06:54:40