我有一个使用 PrimeNg 列表框(p-listbox)显示的列表。它是一个组列表,我通过实现 ngDoCheck 生命周期钩子在其中观察选择的变化。ngDoCheck 下的每一次更改我都创建了一个条件来检查选择是否是特定组(“Group0”)。如果用户选择“Group0”,我想强制选择 p-listbox 回到先前选择的组。我能够确定先前选择的组并将其等同于 selectedGroup 但它不起作用。下面是代码:
export class AppComponent implements OnInit, DoCheck{
selectedGroup: any;
groups: any [] = [];
groupList: SelectItem [] = [] ;
differ: any;
constructor(private differs: KeyValueDiffers) {
this.groups = [
{"groupId": 1, "groupName": "Group1"},
{"groupId": 2, "groupName": "Group2"},
{"groupId": 3, "groupName": "Group3"},
{"groupId": 4, "groupName": "Group4"},
{"groupId": 5, "groupName": "Group5"},
{"groupId": 0, "groupName": "Group0"}
];
this.differ = differs.find([]).create(null);
}
ngOnInit() {
this.groups.forEach(gp=> this.groupList.push({label: gp.groupName, value: gp}));
this.selectedGroup = this.groups[0];
}
ngDoCheck() {
var changesInSelectedGroup= this.differ.diff(this.selectedGroup);
if (changesInSelectedGroup && this.selectedGroup!=undefined) {
if(this.selectedGroup.groupId==0) {
let previousVal: string = this.differ._appendAfter.previousValue;
let currentVal: string = this.differ._appendAfter.previousValue;
this.selectedGroup = this.groups.find(gp=> gp.groupName==previousVal);
// alert('Group0 selected. Selection should go back to previously selected group');
}
console.log(this.differ._appendAfter.previousValue);
}
}
}
我为此创建了一个 plunkr。http://plnkr.co/edit/oLoCEMT4zxqCApUL4Isn?p=preview