Angular4中div点击函数需求:页面加载仅显div-2,点击后切换显示div-1
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,
showDiv1isfalse— so*ngIf="showDiv1"hides div-1, and*ngIf="!showDiv1"makes div-2 visible. - When you click div-2, the
(click)event setsshowDiv1totrue. This triggers the*ngIfdirectives: div-2 disappears (since!showDiv1is 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

