angularselectionmodel

angular selectionmodel .selected not working


I am facing an issue using SelectionModel. Sometimes it works fine and sometimes it does not work. I have spent a lot of time on it. While analyzing I found that sometimes it contains a value in _selected field and sometimes the object does not have _selected field in it. I am not able to figure out how to solve it. If someone knows what is the issue then please let me know. Thank you

if (this.dataSource && this.dataSource.data) {
      this.active = new SelectionModel<RuleListDef>(false, [this.dataSource.data[0]]);
}  

SelectionModel data with out _selected field

{
    "_multiple": false,
    "_emitChanges": true,
    "_selection": {},
    "_deselectedToEmit": [],
    "_selectedToEmit": [],
    "changed": {
        "closed": false,
        "currentObservers": null,
        "observers": [],
        "isStopped": false,
        "hasError": false,
        "thrownError": null
    }
}  

SelectionModel data with _selected field

{
    "_multiple": false,
    "_emitChanges": true,
    "_selection": {},
    "_deselectedToEmit": [],
    "_selectedToEmit": [],
    "changed": {
        "closed": false,
        "currentObservers": null,
        "observers": [],
        "isStopped": false,
        "hasError": false,
        "thrownError": null
    },
    "_selected": [
        {
            "id": "e224ec68",
            "articleId": "934862525",
            "name": "ACCU",
            "company": "ROCH",
            "vendorId": "d58dac44",
            "vendorName": "test",
            "createdOn": "2023-07-04T09:01:41.598037"
        }
    ]
}```


Solution

  • This issue can occur due to not binding the styling method. In my case, it was fixed as follows:

    By changing:

     //Where applyStyles is the styling method for my table row selection
    [ngClassRowCallBackFn]="applyStyles"
    

    To:

     //Where applyStyles is the styling method for my table row selection
    [ngClassRowCallBackFn]="applyStyles.bind(this)"