简体   繁体   English

单击时显示/隐藏元素

[英]Show/Hide element on click

I'm trying to toggle an element to show/hide when I click on the title. 我试图在单击标题时切换显示/隐藏的元素。 So far I have this approach 到目前为止,我有这种方法

<div class="parent" (click)="status=!status" [ngClass]="status ? 'hide' : 'display'">
   <div class="child">
     <p>Info to show or hide</p>
   </div>
</div>

On CSS file I have this 在CSS文件上我有这个

.hide .child {
  display: none;
}

This works fine for what I need when I have one element. 当我只有一个元素时,这可以满足我的需求。 But I want to display several of this items with an *ngFor. 但是我想用* ngFor显示其中几个项目。 When I do that, then variable status is shared and clicking on any of the other elements will toggle all of them. 当我这样做时,变量status被共享,单击任何其他元素将切换所有这些元素。 Since the creation of elements is dynamic, is there any way to limit the scope of status variable to just that element? 由于元素的创建是动态的,是否有任何方法可以将status变量的范围限制为仅该元素? Or is there a better approach to this? 还是有更好的方法呢?

YOu need a status variable in each object 您需要在每个对象中使用status变量

<div *ngFor="let item of items" class="parent" (click)="item.status=!item.status" [ngClass]="item.status ? 'hide' : 'display'">
   <div class="child">
     <p>Info to show or hide</p>
   </div>
</div>

In yours component.ts file, add property status in each array element and assign true to element.status . 在您的component.ts文件中,在每个数组element添加属性status ,然后将true分配给element.status

Then loop over the element s of array using ngFor and use element.status to toggle specefic element as below in your component.html file: 然后遍历所有的element使用数组第ngFor和使用element.status切换specefic element ,如下面的component.html文件:

<div *ngFor="let element of myArray" class="parent" (click)="element.status=!element.status" [ngClass]="element.status ? 'hide' : 'display'">
    <div class="child">
        <p>Info to show or hide</p>
    </div>
</div>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM