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

Angular4中div点击函数需求:页面加载仅显div-2,点击后切换显示div-1

Solution for Toggling Between div-1 and div-2

Looks like you’re working with Angular (given the (click) event binding syntax), so let’s implement this toggle logic cleanly while sticking to your existing structure.

Step 1: Add a visibility tracker to your component

First, declare a boolean property in your component class to control which div is visible. Initialize it to false so div-2 shows up when the page loads:

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

@Component({
  selector: 'app-your-component', // Replace with your actual component selector
  templateUrl: './your-component.component.html',
  styleUrls: ['./your-component.component.css']
})
export class YourComponentComponent {
  // false = show div-2 initially; true = switch to div-1 on click
  showDiv1 = false;
}

Step 2: Update the template with conditional rendering

Modify your HTML to use Angular’s *ngIf directive to toggle visibility based on the showDiv1 property:

<!-- Only display div-1 when showDiv1 is true -->
<div class="div-1" *ngIf="showDiv1">
  <p>content 1</p>
</div>

<!-- Show div-2 by default, hide it once showDiv1 becomes true -->
<div class="div-2" (click)="showDiv1 = true" *ngIf="!showDiv1">
  <p>content 2</p>
</div>

How this works:

  • On page load, showDiv1 is false — so *ngIf="showDiv1" hides div-1, and *ngIf="!showDiv1" makes div-2 visible.
  • When you click div-2, the (click) event sets showDiv1 to true. This triggers the *ngIf directives: div-2 disappears (since !showDiv1 is now false), and div-1 appears.

Alternative: Using [hidden] instead of *ngIf

If you want to keep both elements in the DOM but just toggle their visibility (instead of adding/removing them), use the [hidden] attribute:

<div class="div-1" [hidden]="!showDiv1">
  <p>content 1</p>
</div>
<div class="div-2" (click)="showDiv1 = true" [hidden]="showDiv1">
  <p>content 2</p>
</div>

Note: [hidden] uses CSS display: none to hide elements, while *ngIf completely removes them from the DOM. Pick whichever fits your use case better.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.22 09:48:16