app.component.html
<div>
<div>
<button (click)="toggle()">展开/折叠1</button>
<div [@collapsedExpanded]="collapsed ? 'collapsed' : 'expanded'">
这是一段测试内容 这是一段测试内容 这是一段测试内容 这是一段测试内容 这是一段测试内容
</div>
</div>
<div>
<button (click)="toggle()">展开/折叠2</button>
<div [@collapsedExpanded]="collapsed ? 'collapsed' : 'expanded'">
这是一段测试内容 这是一段测试内容 这是一段测试内容 这是一段测试内容 这是一段测试内容
</div>
</div>
</div>
因为两个button点击触发的是同一个事件, 所以这两段内容现在效果是同时展开或折叠
app.component.ts
import { Component } from '@angular/core';
import { collapsedExpanded } from './animations';
@Component({
selector: 'rxc-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.scss'],
animations: [collapsedExpanded]
})
export class AppComponent {
collapsed = false;
toggle() {
this.collapsed = !this.collapsed;
}
}
animations.ts
import { animate, state, style, transition, trigger } from "@angular/animations";
export let collapsedExpanded = trigger("collapsedExpanded", [
state("collapsed", style({
height: 0,
overflow: "hidden"
})),
state("expanded", style({
height: "*",
overflow: "auto"
})),
transition("collapsed => expanded", animate("100ms linear")),
transition("expanded => collapsed", animate("100ms linear"))
]);
现在需要实现一种类似于手风琴的效果, 点击按钮只展开当前按钮下的div, 折叠其他所有div, 有没有什么可实现的方式?
我目前唯一能想到的是在 ts
中定义多个 collapsed
, 在每个 toggle()
事件中传入对应的 collapsed
来控制单个组件的展开和其他组件的折叠, 但是这方法太麻烦了...