我正在制作手风琴组件。我想要的只是一个手风琴(总共有三个)一次打开。换句话说,任何开放式手风琴在点击除当前打开的手风琴之外的任何手风琴时都会崩溃。
现在,我能够打开/关闭这些手风琴,但我无法弄清楚如何“选择”它们以便应用“崩溃”类(如果当前未被选中)。我的选择输入在第一次点击时是假的(在Augury中显示为否则)。
手风琴group.component.ts
import { AccordionComponent } from './../accordion/accordion.component';
import { Component, Input } from '@angular/core';
@Component({
selector: 'app-accordion-group',
templateUrl: './accordion-group.component.html',
styleUrls: ['./accordion-group.component.css']
})
export class AccordionGroupComponent {
@Input() measures;
selected
select(i){
this.selected = i;
}
}
手风琴group.component.html
<app-accordion
*ngFor="let item of items; let i = index"
[item]="item"
[selected]="i === selected"
(click)="select(i)">
</app-accordion>
accordion.component.ts
import { Component, Input } from "@angular/core";
@Component({
selector: "app-accordion",
templateUrl: "./accordion.component.html",
styleUrls: ["./accordion.component.css"]
})
export class AccordionComponent {
@Input() item;
@Input() index;
@Input() selected //this needs to receive true on selected component on click
expand: string = "";
isOpen = false;
handleExpansion() {
console.log(this.selected) //logs false on first click
this.isOpen = !this.isOpen;
this.isOpen ? (this.expand = "expand") : (this.expand = "collapse");
}
}
accordion.component.html
<div
(click)="handleExpansion()"
class="accordion noHighlight {{expand}}">
</div>
答案 0 :(得分:1)
如上所述,您遇到此问题的原因是浏览器DOM事件冒出来。因此,AccordionComponent
中的点击处理程序将在AccordionGroupComponent
中的点击处理程序之前执行。
有很多方法可以完成你想要做的事情,所以我将a quick Plunker for you与一种方法放在一起。
它的要点是该组确定哪个手风琴被扩展(如果有的话):
@Component({
selector: 'app-accordion-group',
template: `
<app-accordion *ngFor="let accordion of accordions" [title]="accordion.title"
[isExpanded]="accordion === expandedAccordion"
(expandClick)="processExpandClick(accordion, $event)">
<p>{{ accordion.description }}</p>
</app-accordion>
`
})
export class AccordionGroupComponent {
@Input() accordions: Accordion[];
expandedAccordion: Accordion = null;
processExpandClick(accordion: Accordion, isExpanded: boolean) {
this.expandedAccordion = isExpanded ? accordion : null;
}
}
当扩展/崩溃事件发生时,手风琴会发出事件,允许该组确定要展开/折叠的内容:
@Component({
selector: "app-accordion",
template: `
<div class="accordion" [class.expanded]="isExpanded">
<div (click)="handleClick()">
<span *ngIf="!isExpanded">+</span>
<span *ngIf="isExpanded">-</span>
{{ title }}
</div>
<div class="accordion__content">
<ng-content></ng-content>
</div>
</div>
`,
styles: [`
.accordion__content {
height: 0;
overflow: hidden;
}
.expanded .accordion__content {
height: auto;
}
`]
})
export class AccordionComponent {
@Input() title;
@Input() isExpanded = false;
@Output() expandClick = new EventEmitter<boolean>();
handleClick() {
this.expandClick.emit(!this.isExpanded);
}
}