这段代码有两个问题:
您只有一个属性负责每个面板的折叠状态。这样就不可能单独控制它们了。
您有单向绑定,因此当您在视图中手动折叠面板时,模型不会更新。我修复了您的代码并分叉了 plunker:https://plnkr.co/edit/rfiVj8vEIBDOZ8rIHV5i
主要思想是:
拥有动态模板以保持您的 html 干燥:
<p-panel *ngFor="let panel of panels"
[header]="panel.name"
[toggleable]="true"
[(collapsed)]="panel.isCollapsed" <== notice the "banana-in-a-box" notation [()], which allows two-way binding
[style]="{'margin-bottom':'20px'}">
{{ panel.text }}
</p-panel>
export class AppComponent {
panels = [
{
name: 'Panel 1',
isCollapsed: false,
text: `The story begins as Don Vito Corleone...`
},
{
name: 'Panel 2',
isCollapsed: false,
text: `The story begins as Don Vito Corleone...`
},
{
name: 'Panel 3',
isCollapsed: false,
text: `The story begins as Don Vito Corleone...`
},
{
name: 'Panel 4',
isCollapsed: false,
text: `The story begins as Don Vito Corleone...`
},
] // you can also move this to a separate file and import
constructor() {
}
expandAll(){
this.panels.forEach(panel => {
panel.isCollapsed = false;
});
}
collapseAll(){
this.panels.forEach(panel => {
panel.isCollapsed = true;
});
}
}
更新
如果您不想从面板中提取文本,则不必这样做,但在这种情况下,您将无法使用 *ngFor 并且您必须将每个面板的状态存储在您的某些数据结构中组件。
你可以有这样的东西:
panelsCollapsed = [
{
isCollapsed: false,
},
{
isCollapsed: false,
},
{
isCollapsed: false,
},
{
isCollapsed: false,
}, // this can also be just an arry of booleans, I kep it as an object in case you want to add other fields to it
那么在你的标记中你会有:
<p-panel header="Panel 1" [toggleable]="true" [collapsed]="panelsCollapsed[0].isCollapsed" [style]="{'margin-bottom':'20px'}">
The story begins as Don Vito Corleone...
</p-panel>
<p-panel header="Panel 2" [toggleable]="true" [collapsed]="panelsCollapsed[1].isCollapsed" [style]="{'margin-bottom':'20px'}">
The story begins as Don Vito Corleone...
</p-panel>
所有展开/折叠的方法保持不变。