我希望这样的事情能够发挥作用:
<button (click)="myAccordionGroup.expandAll()">Expand all</button>
<ion-accordion-group #myAccordionGroup>
<ion-accordion>
<ion-item slot="header">
<ion-label>First Accordion</ion-label>
</ion-item>
<div slot="content">First accordion content</div>
</ion-accordion>
<ion-accordion>
<ion-item slot="header">
<ion-label>Second Accordion</ion-label>
</ion-item>
<div slot="content">Second accordion content</div>
</ion-accordion>
</ion-accordion-group>
但是
IonAccordionGroup.expandAll
并不作为方法存在。事实上,在撰写本文时,IonAccordionGroup
并未公开任何方法。
作为解决方法,我设法通过手动创建为每个
ion-accordion
分配值,然后将 ion-accordion-group
的值设置为包含所有这些值的数组来实现。为了一次折叠所有手风琴,我将 ion-accordion-group
的值设置为空数组。
但我正在寻找一种方法:
ion-accordion
元素分配值。ion-accordion-group
状态。在撰写本文时,
IonAccordionGroup
尚未提供可让您按照您所描述的方式进行操作的方法。
您的“解决方法”是正确的方法。
您可以创建自定义 Angular 指令来降低复杂性:
import { ContentChildren, Directive, QueryList } from "@angular/core";
import { IonAccordion, IonAccordionGroup } from "@ionic/angular/standalone";
@Directive({
selector: "[appAccordionGroupToggle]",
exportAs: "appAccordionGroupToggle",
standalone: true,
})
export class AccordionGroupToggleDirective {
// get a reference to the ion-accordion instances inside
@ContentChildren(IonAccordion) accordions!: QueryList<IonAccordion>;
// get a reference to the ion-accordion-group instance
constructor(private host: IonAccordionGroup) {}
expand() {
// setting the value of the ion-accordion-group to an array of all the
// ion-accordion values will expand all ion-accordions
this.host.value = this.accordions.map((accordion) => accordion.value);
}
collapse() {
// setting the value of the ion-accordion-group to an empty array will
// collapse all ion-accordions inside
this.host.value = [];
}
}
在你的组件中,你可以像这样使用它:
@Component({
...
standalone: true,
imports: [
...
AccordionGroupToggleDirective,
],
})
export class MyComponent {
}
<button (click)="toggler.expand()">Expand all</button>
<button (click)="toggler.collapse()">Collapse all</button>
<ion-accordion-group appAccordionGroupToggle
#toggler="appAccordionGroupToggle">
<ion-accordion>
<ion-item slot="header">
<ion-label>First Accordion</ion-label>
</ion-item>
<div slot="content">First accordion content</div>
</ion-accordion>
<ion-accordion>
<ion-item slot="header">
<ion-label>Second Accordion</ion-label>
</ion-item>
<div slot="content">Second accordion content</div>
</ion-accordion>
</ion-accordion-group>