我正在制作 Accordion 以在 Angular 应用程序中使用 javascript 制作可折叠的 div..
为此,如果单击Parent One
或任何其他父名称上的按钮未打开它..
HTML:
<div *ngFor="let item of data">
<button class="accordion"> {{item.parentName}} </button>
<div class="panel" *ngFor="let child of item.childProperties">
<p> {{child.propertyName}} </p>
</div>
</div>
条件:
import { Component, OnInit } from '@angular/core';
@Component({
selector: 'my-app',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
data: any =
[
{
"parentName": "Parent One",
"childProperties":
[
{ "propertyName": "Property One" },
{ "propertyName": "Property Two" }
]
},
{
"parentName": "Parent Two",
"childProperties":
[
{ "propertyName": "Property Three" },
{ "propertyName": "Property Four" },
{ "propertyName": "Property Five" },
]
},
{
"parentName": "Parent Three",
"childProperties":
[
{ "propertyName": "Property Six" },
{ "propertyName": "Property Seven" },
{ "propertyName": "Property Eight" },
]
}
]
ngOnInit() {
var acc = document.getElementsByClassName("accordion");
var i;
for (i = 0; i < acc.length; i++) {
acc[i].addEventListener("click", function () {
this.classList.toggle("active");
var panel = this.nextElementSibling;
if (panel.style.maxHeight) {
panel.style.maxHeight = null;
} else {
panel.style.maxHeight = panel.scrollHeight + "px";
}
});
}
}
}
注意:因为我是 angular 的新手,所以我用 javascript 的方式来制作它。所以请帮助我使用纯 angular 和 typescript 来实现结果..
工作 stackblitz https://stackblitz.com/edit/angular-lp3riw
你可以在演示中看到父按钮是可见的,但如果你点击按钮,它不会展开......
还在下面列出了具有静态值的工作可折叠按钮..
如何使用 Angular 和 typescript 方式(没有任何第三方或 jquery)制作一个可折叠的 Accordion ,就像给定的 stackblitz 静态值一样。
最佳答案
将函数保留在 ngAfterViewInit
而不是 ngOnInit
中。查看更新 stackblitz
问题是在 ngOnInit 上, View 没有完全绘制,并且您没有获得要绑定(bind)函数的所有元素。
ngAfterViewInit() {
var acc = document.getElementsByClassName("accordion");
var i;
for (i = 0; i < acc.length; i++) {
acc[i].addEventListener("click", function () {
this.classList.toggle("active");
var panel = this.nextElementSibling;
if (panel.style.maxHeight) {
panel.style.maxHeight = null;
} else {
panel.style.maxHeight = panel.scrollHeight + "px";
}
});
}
}
使用 angular 如下所示。
在按钮上保留一个点击功能,并绑定(bind)一个属性 isActive
到相应的数组元素。然后根据 isActive 是否具有值 true/false 显示/隐藏 Accordion 。
<div *ngFor="let item of data;let i = index;">
<button class="accordion" (click)="toggleAccordian($event, i)"> {{item.parentName}} </button>
<div class="panel" *ngFor="let child of item.childProperties" hide="!item.isActive">
<p> {{child.propertyName}} </p>
</div>
</div>
toggleAccordian(event, index) {
var element = event.target;
element.classList.toggle("active");
if(this.data[index].isActive) {
this.data[index].isActive = false;
} else {
this.data[index].isActive = true;
}
var panel = element.nextElementSibling;
if (panel.style.maxHeight) {
panel.style.maxHeight = null;
} else {
panel.style.maxHeight = panel.scrollHeight + "px";
}
}
关于javascript - Angular 可折叠 Accordion ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53369784/