私はAngularアコーディオンコンポーネントを構築していますクリックで開きます(合計3つのアコーディオンがあり、一度に開く「選択された」アコーディオンは1つだけです)。 2回目のクリックで現在開いているアコーディオンを閉じられるようにしたいです。今のところ私は一度だけ開くことができます。
accordion-group.component.ts
import { Component, Input } from "@angular/core";
@Component({
selector: "app-accordion-group",
templateUrl: "./accordion-group.component.html",
styleUrls: ["./accordion-group.component.css"]
})
export class AccordionGroupComponent {
items = ["accordion1", "accordion2", "accordion3"]
selectedIndex;
select(i){
this.selectedIndex = i;
}
}
accordion-group.component.html
<app-accordion
*ngFor="let item of items; let i = index"
(click)="select(i)"
[selectedIndex]="selectedIndex"
[index]="i"
[item]="item">
</app-accordion>
accordion.component.html
<div
class="accordion"
[ngClass]="currentClass">
</div>
accordion.component.ts
import { Component, Input, OnChanges } from "@angular/core";
@Component({
selector: "app-accordion",
templateUrl: "./accordion.component.html",
styleUrls: ["./accordion.component.css"]
})
export class AccordionComponent implements OnChanges {
@Input() item;
@Input() selectedIndex;
@Input() index;
currentClass;
isOpen = false;
ngOnChanges(){
this.handleExpansion()
}
handleExpansion() {
this.isOpen = true;
if (this.isOpen && this.selectedIndex === this.index) this.currentClass = "expand";
else this.currentClass = "collapse"
}
}
回答:
回答№1は1私がドキュメントから指摘したいのは、これです。
Angular calls its ngOnChanges() method whenever it detects changes to input
properties of the component (or directive).
そのため、2度目に同じアコーディオンコンポーネントをクリックしても、その入力プロパティはまったく変更されません。だからあなたは追加する必要があります handleExpansion
クリックでも。
handleExpansionロジックも更新しました
handleExpansion() {
// check if the component is selected or not
if (this.selectedIndex === this.index) {
// check if the component was open or not after seletion
// if it was open collapse it and return
if (this.isOpen) {
this.currentClass = "collapse";
this.isOpen = false;
return
}
// if the component is selected for first time expand it
this.currentClass = "expand";
this.isOpen = true;
}
else {
// if the component is not selected collapase it and
this.currentClass = "collapse";
// close it in case if it was open earlier
this.isOpen = false;
}
}
ここに働いている 例
回答№2の場合は0
あなたはモデルステートメントを使うことができます、ちょうどあなたのアコーディオンの配列をこのようにオブジェクトに変更してください:
interface Accordion {
id: number,
index: number,
show: boolean
}
それから私たちはこれが好き:
let accordions: Accordion[] = [];
accordions.push({"id": 1, "index": 0, "show": false});
accordions.push({"id": 2, "index": 1, "show": false});
accordions.push({"id": 3, "index": 2, "show": false});
それからプロパティを変更します show
クリックしたアコーディオンを表示/非表示にします。
で選択したアコーディオンをゲット show
本当のようにそれをに設定 false
:
let index_opened = accordions.findIndex(a => a.show);
accordions[index_opened].show = false;