我正在使用多个面板,并为 expandAll / collapseAll 面板添加了功能。我的问题是:
让我们说:
1)我展开所有面板
2)现在,我崩溃仅第二个面板
3)现在我点击 ExpandAll按钮(期望展开所有面板)。
问题:按照上述步骤操作后,我无法展开面板。
这是我的代码:
<button (click)="collapseAll()">ExpandAll</button>
<button (click)="expandAll()">CollapseAll</button>
答案 0 :(得分:2)
此代码有两个问题:
您只有一个属性负责每个面板的折叠状态。这样就无法单独控制它们。
您具有单向绑定,因此在视图中手动折叠面板时,模型不会更新。我修改了你的代码并分叉了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>
扩展/折叠所有方法将保持不变。