问题是您正在与[expanded]
. 因此,每次更改检测运行时,它都会shouldBeExpanded
一次又一次地检查该功能。
选项1:
如果您想继续使用shouldBeExpanded
for [expanded] 标志,可以使用OnPush
更改检测策略。
当我对此进行测试时,扩展和崩溃几乎没有故障。在演示中试用
ts:
import {Component, ChangeDetectionStrategy} from '@angular/core';
import {Http} from '@angular/http'
import {bootstrap} from '@angular/platform-browser-dynamic';
import 'rxjs/add/operator/map'
@Component({
selector: 'material-app',
templateUrl: 'app.component.html',
changeDetection: ChangeDetectionStrategy.OnPush
})
Plunker 演示
选项 2:
您可以创建一个数组来跟踪每次扩展的标志,而不是与函数绑定。您可以使用OnInit
存储在localstorage
. 如果值不在本地存储中,您可以分配一个默认标志。每当扩展状态发生变化时,在数组和localstorage
.
ts:
export class AppComponent implements OnInt {
private version: any;
items = ["a1", "a2", "a3"];
expansionFlag = [];
constructor(http: Http) {
// Display the currently used Material 2 version.
this.version = http
.get('https://api.github.com/repos/angular/material2-builds/commits/HEAD')
.map(res => res.json())
}
ngOnInit(){
for(let i = 0; i <this.items.length; i++){
let flag = JSON.parse(localStorage.getItem(this.items[i]));
console.log(flag);
if(flag != undefined && flag != null){
this.expansionFlag.push(flag);
}
else
this.expansionFlag.push(false);
}
console.log(this.expansionFlag)
}
openPanel(name, index) {
console.log(name, 'is now open')
this.expansionFlag[index] = true;
localStorage.setItem(name, 'true');
}
closePanel(name, index) {
console.log(name, 'is now closed');
this.expansionFlag[index] = false;
localStorage.setItem(name, 'false');
}
}
更新[expanded]
html中的每个:
[expanded]="expansionFlag[0]"
[expanded]="expansionFlag[1]"
[expanded]="expansionFlag[2]"
Plunker 演示