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

Angular:如何根据含指定类与ID的元素控制另一元素显隐?

实现方案

一、纯CSS方案

利用CSS的:has()选择器(现代主流浏览器已兼容),默认隐藏.content,当页面中存在同时带有active类和mainid ID的元素时,显示它:

/* 默认隐藏.content */
.content {
  display: none;
}

/* 当存在#mainid.active元素时,显示.content */
body:has(#mainid.active) .content {
  display: block;
}

你之前的CSS写法逻辑混乱,错误地将.content和目标元素的选择器混在一起,且没有正确利用:has()检测目标元素的存在。

二、Angular *ngIf + TypeScript方案

通过TypeScript判断目标元素是否存在,再用*ngIf指令控制.content的显示,更符合Angular的响应式开发理念:

  1. 修改组件模板:
<div>
  <div class="content" *ngIf="showContent"> this div element should show up only below one is there </div>
</div>

<div>
  <div>
    <div class="active" id="mainid"> open content </div>
  </div>
</div>
  1. 组件类代码:
import { Component, OnInit } from '@angular/core';

@Component({
  selector: 'app-your-component',
  templateUrl: './your-component.component.html',
  styleUrls: ['./your-component.component.css']
})
export class YourComponent implements OnInit {
  showContent = false;

  ngOnInit(): void {
    // 初始化时检查目标元素
    this.checkTargetElement();

    // 若active类是动态添加/移除的,用MutationObserver监听变化
    const target = document.getElementById('mainid');
    if (target) {
      const observer = new MutationObserver(() => {
        this.checkTargetElement();
      });
      observer.observe(target, { attributes: true, attributeFilter: ['class'] });
    }
  }

  private checkTargetElement(): void {
    this.showContent = !!document.querySelector('#mainid.active');
  }
}

如果active类是通过Angular绑定(比如[class.active]="isActive")实现的,可直接将isActive绑定到*ngIf,无需DOM查询。

三、TypeScript直接操作DOM(不推荐)

若需直接操作DOM,可在组件中获取元素并控制显示,但不符合Angular最佳实践:

import { Component, OnInit, ElementRef } from '@angular/core';

@Component({
  selector: 'app-your-component',
  templateUrl: './your-component.component.html',
  styleUrls: ['./your-component.component.css']
})
export class YourComponent implements OnInit {
  constructor(private el: ElementRef) {}

  ngOnInit(): void {
    const contentEl = this.el.nativeElement.querySelector('.content');
    const targetEl = document.querySelector('#mainid.active');
    if (contentEl) {
      contentEl.style.display = targetEl ? 'block' : 'none';
    }

    // 动态监听类变化的逻辑同第二种方案
  }
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.22 13:50:25