Angular 7 – Dynamic Sorting Array

I have an array of objects with properties like name, lastUpdated, etc. The objects are listed in a grid that has sorting options for each of these properties. I have an option also to add a new object to the list. What I want to do is to add it ordered on the list following the sorting criteria applied on that moment.

For example if I have this list:

aaaa
bbbb
hhhh

with a sorting criteria of name ASC and I add a name like cccc I want my list like this:

aaaa
bbbb
cccc
hhhh

And the same with any sorting criteria applied.

When I apply a sorting criteria I save it on my component on a variable:

sortingCriteria;

Then when I add a new element to the list I do like:

this.list.sort((a, b) => a.Name.localeCompare(b.Name));

That orders by name but I need to apply that sortingCriteria saved before on this sorting method to order the list properly. Is there any way to use it as a property of the list’s objects? Or something to do to filter my list with that sortingCriteria saved? I’ve tried to use my sorting method which is this one:

sortGrid(event) {
    this.sortingCriteria = event.field;
    if (this.list&& this.cols && this.list.length > 0 && this.cols.length > 0) {
      const col = this.cols.filter(x  => x.field === event.field)[0];

      if (col) {
        this.colIndexSelected = col.colIndex;
      }
    }
  }

But It’s not working I don’t know why.

Source: New feed
Source Url Angular 7 – Dynamic Sorting Array