我在Angular 2中制作手风琴而我想要完成的是当我点击其中一支手风琴时,手风琴将打开,所有其他打开的手风琴将被关闭(所以基本上是先前开放的手风琴将被关闭)。没有DOM操作。
我现在如何做到这一点:我有一个名为' classActive'的类型布尔值我在点击时切换为真或假。
(注意:手风琴使用ngFor
循环
HTML
<div class="accordion" [ngClass]="{'is-active' : classActive}">
<div class="accordion__container">
<div class="accordion__header" (click)="toggleClass($event)">
<h2 class="accordion__heading">{{ name }}</h2>
</div>
<div class="accordion__content">
{{ content }}
</div>
</div>
</div>
JS
@Component({
selector: 'accordion',
templateUrl: './accordion.component.html',
styleUrls: ['./accordion.component.scss']
})
export class AccordionComponent implements OnInit {
classActive: boolean = false;
toggleClass(event) {
event.preventDefault();
this.classActive = !this.classActive;
}
}
SCSS
.accordion {
height: 100px;
overflow: hidden;
transition: height .3s cubic-bezier(1, 0, .41, 1.01);
&.is-active {
height: 200px;
.accordion__content {
opacity: 1;
}
}
&__header {
cursor: pointer;
height: 100px;
padding: 0 $p-container;
position: relative;
}
&__heading {
text-transform: lowercase;
line-height: 100px;
pointer-events: none;
}
&__content {
opacity: 0;
transition: opacity .6s;
padding: $p-container;
}
}
我认为解决方案是设置所有“classActive”&#39;如果为false,则将单击的设置为true。但这可能吗?
答案 0 :(得分:1)
正如评论中所提到的,问题在于您创建了一个变量来处理多个元素。
最简单的解决方案恕我直言,将function
修改为&#34;保存&#34;点击当前索引如下:
<强>组件:强>
activeIndex: number = 0; // The accordion at index 0 will be open by default
toggleClass(i: number): void {
this.activeIndex = i;
}
因此,在您的模板中,您只需将[ngClass]
修改为:
[ngClass]="{'is-active': activeIndex === i}"
<强>模板:强>
<div *ngFor="let yourVariable of yourArray, let i = index">
<div class="accordion" [ngClass]="{'is-active': activeIndex === i}">
<div class="mood__container">
<div class="mood__header" (click)="toggleClass(i)">
<h2 class="mood__heading">{{ name }}</h2>
</div>
<div class="accordion__container>
{{ content }}
</div>
</div>
</div>
</div>
检查以下完整代码:
答案 1 :(得分:0)
[ngClass]="{'is-active' : activeIndex === i, 'is-dactive' : activeIndex != i}">
togglePopover(event, i: number) {
event.preventDefault();
this.activeIndex = i
console.log(this.activeIndex);
}