Search code examples
angularangular-material

Sorting of MatCheckbox list in Angular


Currently I am following the Answer mentioned in the below link

matcheckbox

How can I achieve the sorting of checked checkboxes first in Alphabetical order and unchecked checkboxes second in Alphabetical order on click/unclick of the mat-checkbox control.

I would like to have sorting on 2 separate sets of checkboxes instead of only single subscribers for the Answer provided in the link above.

The name of the items can have Aplhanumeric characters.

Getting below error for the Answer provided..

Error

Displaying of Subscribers..

Subscribers

EDIT

Now, I am using this below code in the function of sort() and for the first time, on clicking of checkbox, it is automatically getting unchecked and for the 2nd time, it works..

sort()
{
    setTimeout(()=>{
      this.selectedSubscribers = this.allSubscribers
        .filter((x: any) => x.checked)
        .sort((a: any, b: any) => {
          return a.checked && b.checked ? a.name - b.name : 0;
      });
      this.unselectedSubscribers = this.allSubscribers
        .filter((x: any) => !x.checked)
        .sort((a: any, b: any) => {
          return a.checked && b.checked ? a.name - b.name : 0;
      });
    })
}

SECOND EDIT

Getting the below error when I use BrowserModule in Submodule

BrowserModule


Solution

  • sort function should return 1 (if less), -1(if more) or 0 (if equal). We need take carefull when use concatenated ternary operators. If you have two separates arrays only use the property name:

    sort((a:any,b:any)=>a.name>b.name?1:a.name<b.name?-1:0
    

    It's the same like

    sort((a:any,b:any)=>{
       if (a.name>b.name)
          return 1
       else{
         if (a.name<b.name)
            return -1
         }
         else
            return 0
      }
    }
    

    Or if we can not concatenate else -a return yet return a value-

    sort((a:any,b:any)=>{
       if (a.name>b.name)
          return 1
    
       if (a.name<b.name)
            return -1
    
       return 0
    }
    

    Well, we know that there no two objects with the same name, so we can simplify

    sort((a:any,b:any)=>a.name>b.name?1:-1