0

I am building a basic inventory tracking web app with Angular and I'm running into an issue. I want my main page to immediately display the most recent inventory data. The app is in its infancy, so the inventory data is being fed to it via a mock inventory list as shown here:

import { Inventory } from './inventory';

export const INVENTORY: Inventory[] = [
    { item: 'generic', type: 'sticker', count: 14 },
    { item: 'sonny', type: 'pti', count: 9 },
    { item: 'ribbon', type: 'pti', count: 4 },
    { item: 'sonny', type: 'box', count: 56 },
    { item: 'generic', type: 'box', count: 6 },
    { item: 'salad', type: 'box', count: 12 },
    { item: 'foam', type: 'other', count: 39 },
    { item: 'glue', type: 'other', count: 41 },
    { item: 'twine', type: 'other', count: 2 }
];

The list includes a type attribute so that I can filter by type later on.

To display this list, I'm using the HTML as follows:

<ul class="inventory">
    <h3>Stickers</h3>
    <li *ngFor="let item of inventory">
        <a *ngIf="item.type === 'sticker'>
            <span class="badge">{{item.item}}</span> {{item.count}}
        </a>
    </li>
</ul>

As you can see, I create a list element and call *ngFor="let item of inventory" to iterate over the entire list. Next *ngIf checks if the item type is 'sticker' and if so, it writes the item.item and item.count variables to the display. The span class="badge" is for css formatting purposes only.

The problem is, this displays the blank css attributes for every item in the list, and populates the ones where type === 'sticker'. I only want to display those items with type = 'sticker', and make the rest invisible. You can see what I mean at the image below.

Web output showing css formatted list items for all items and populating only the elements of the list with type === 'sticker'

How can I do this?

  • Nesting `

    ` withing the `
      ` is invalid HTML markup. https://stackoverflow.com/questions/6056142/is-anything-except-lis-allowed-in-a-ul

    – Canica Oct 31 '19 at 19:41

1 Answers1

0

To resolve this issue, Use below CSS in component.css

ul li{
  list-style: none
}

Sample working ocde for reference- https://stackblitz.com/edit/angular-cql9hi?file=src/app/app.component.css

Option 2: Use ng container and move *ngFor to ng-container and *ngIf to li element

<ul class="inventory">
    <h3>Stickers</h3>
    <ng-container *ngFor="let item of inventory">
    <li *ngIf="item.type === 'sticker'">
        <a>
            <span class="badge">{{item.item}}</span> {{item.count}}
        </a>
    </li>
    </ng-container>
</ul>

working sample code for reference - https://stackblitz.com/edit/angular-x4lzgc?file=src/app/app.component.html

ng-container allows to wrap elements like block without creating new element

Please refer this link for more details on ng-container - <ng-container> vs <template>

Naga Sai A
  • 10,771
  • 1
  • 21
  • 40