I met a very interesting in my angular2 application, I simplify the situation here.
This is AppComponnet
export class AppComponent {
tabs: any = [];
viewModes = [
{ label: "列表查看"},
{ label: "树状图" },
];
constructor(private changeRef: ChangeDetectorRef) {}
addTab() {
var worker = new Worker("worker.js");
worker.postMessage("");
worker.onmessage = (event) => {
this.tabs.push({
label: 'label'
})
this.changeRef.detectChanges();
}
}
currentMode: any;
selectViewMode(mode: any) {
if (this.currentMode) {
this.currentMode.selected = false;
}
mode.selected = true;
this.currentMode = mode;
}
}
And this is template
<div *ngFor="let tab of tabs">
<ul>
<li *ngFor="let item of viewModes">
<a (click)="selectViewMode(item)" [style.background]="item.selected ? '#f69c55' : ''"> {{item.label}} </a>
</li>
</ul>
</div>
<button (click)="addTab()">Add Tab</button>
I push a new tab to tabs when Worker done. And angular2 won't do change detect after Worker onmessage callback, and I must trigger change detection manually.
But after that, the background of list in the added tab won't change after click(the callback function was executed, so it is that the change detection does not work).
And if I do something else like click the Add Tab button again, the change detection will work and set the list background as expect.
And if I do not trigger change detection manually. After pushing tab, do something else(eg. click button again) to trigger change detection. And now the list will show, and the background change works well.
I know the key is manually call change detection after Worker execute, but I don't know what happened in detail cause the list background change detection do not work.