Angular 4实现菜单点击后为指定section添加/切换active类
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
setActiveLangmethod updates theactiveLangproperty. - The
ngClassdirective on each section checks ifactiveLangmatches its language ID. If it does, theactiveclass 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

