0

我有一个使用 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

4

1 回答 1

5

Angular 的NgModel指令与相应的指令通信ControlValueAccessor如下:

在此处输入图像描述

所以我建议按如下方式解决您的问题:

模板.html

将模板引用变量添加到您的p-listbox元素

<p-listbox #listBox [options]="groupList" [(ngModel)]="selectedGroup"></p-listbox>

组件.ts

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);
  }
}

覆盖onChangeonModelChange在你的情况下)事件ControlValueAccessor

@ViewChild('listBox') accessor: Listbox;
@ViewChild('listBox', { read: NgModel }) model: NgModel;

ngOnInit() {
  ...
  this.accessor.registerOnChange = (fn: (val: any) => void) => {
    this.accessor.onModelChange = (val) => {
      if(val && val.groupId === 0) {
        this.model.control.setValue(this.model.value);
        return;
      }
      return fn(val);
    };
  }

Plunker 示例

于 2017-08-07T05:07:44.207 回答