0

I have an array of items, each with a category that is sometimes shared. What I want to do is group the items in my template by their category. Currently I'm achieving this by simply looping the array for each category, but that's inefficient. I want to loop the array once only, and output to the different sections respectively. I can't seem to search a clear way to do this. Here's a rough outline of what I'm hoping to do:

<ng-container *ngFor="let item of items">
  <!--
    The checkbox below needs to be output to one of the proceeding
    4 sections based on its category, I assume using a switch.
  -->
  <mat-checkbox
    class="item-toggle"
    [checked]="item.enabled"
    (change)="toggleItem(item)"
    >{{ item.name }}</mat-checkbox
  >
</ng-container>

<h3>Category 1</h3>
<section class="item-choices" #category1></section>

<h3>Category 2</h3>
<section class="item-choices" #category2></section>

<h3>Category 3</h3>
<section class="item-choices" #category3></section>

<h3>Category 4</h3>
<section class="item-choices" #category4></section>

Is there a way to do this with the default directives available?

Edit: Updated the example. I wanted to highlight that I do not wish to duplicate the category sections. I wanted to direct the output to the 4 separate locations. I can achieve this now by either running 4 loops, once for each category. Or, in my ts, I can filter the array into subarrays for each category.

I was hoping there would be a way to do this with the template or directives alone.

KDill
  • 1
  • 2
  • You will use something known as ngFor – Ashutosh Kumar Jan 03 '21 at 09:40
  • @AshutoshKumar thanks, but that's not the question I've asked. – KDill Jan 03 '21 at 09:58
  • When it comes to grouping and sorting, Angular and JS have lots of tools to perform the conversions. But you are looking efficiency as I always do. I came to conclusion that lots of data manipulation shouldn't be done on the client, but at your data layer (EF / DB et al). If you have access to this layer, a simpler method might be to perform the grouping there, instead of at the Angular app. – Darren Street Jan 03 '21 at 11:51

1 Answers1

0

Have the selected items saved in an array, then bind to the selection. So, something like this may work:

checked property, where checked is an array of either items or indexes for items.

Then, bind to the section using ngModel. In the first instance, you would have the first section be like:

<section class="item-choices" [(ngModel)]="checked[0]" #category1></section>

and in the second:

<section class="item-choices" [(ngModel)]="items[checked[0]]" #category1></section>

basically, bind your selected choice to the ts and then use the bound property to bind the sections

PMO1948
  • 2,210
  • 11
  • 34