Angular ng-if change span text

All we need is an easy explanation of the problem, so here it is.

I have this JSON file that I am taking objects as products from. When displaying the sizes of the products I want to change a span from “sizes:” to “kids:” when the json object has “kids”: “1”.

<div class="sizes-wrap">
        <span class="size-label"><span>sizes:</span>
        <span class="sizes">{{ item.sizes }}</span>

this code prints Sizes: and the sizes from the json e.g. “128 cm,140 cm,152 cm,164 cm”

I want when in the json object “kids” has a value of 1 to change the word “sizes” to “kids” in the html.

<div class="sizes-wrap">
        <span class="size-label"><span>kids:</span>
        <span class="sizes">{{ item.sizes }}</span>

Here is an one of the json objects:

  "kids": "0",
  "name": "Product name",
  "sizes": "Small,Medium,Large,X-Large,XX-Large,3XL",
  "kid_adult": "0",
  "free_porto": "0",
  "price": "649,00",
  "package": "0",
  "delivery": "1-2 dage",
  "price_old": "0,00",
  "id": "133714",
  "women": "0"

This is what I wanted to achieve after all:

<div class="sizes-wrap">
        <span ng-if=" == 0 && item.kid_adult == 0 && item.women == 0" class="size-label"><span>sizes:</span></span>
        <span ng-if=" == 1" class="size-label"><span>kids:</span></span>
        <span ng-if="item.kid_adult == 1" class="size-label"><span>adult kids:</span></span>
        <span ng-if="item.kid_adult == 1" class="size-label"><span>women:</span></span>
        <span class="sizes">{{ item.sizes }}</span>

How to solve :

I know you bored from this bug, So we are here to help you! Take a deep breath and look at the explanation of your problem. We have many solutions to this problem, But we recommend you to use the first method because it is tested & true method that will 100% work for you.

Method 1

With a javascript expression, in this case using a ternay operator.

    {{ user.biography ? user.biography : 'Without information' }}

Method 2

This should work for you:

<div class="sizes-wrap">
    <span class="size-label">
        <span ng-if=" == 0">sizes:</span>
        <span ng-if=" == 1">kids:</span> 
    <span class="sizes">{{ item.sizes }}</span>

Method 3

 <span ng-if=" === 1">kids:</span>
 <span ng-if=" !== 1">sizes:</span>

Maybe, like this, but better to send word with json and insert it, like this:

<span class="size_word">{{data.size_word}}</span>

Method 4

Instead of using multiple *ngIf you could use an *ngIf; else.
Example from Angular Docs v11:

<div *ngIf="condition; else elseBlock">Content to render when condition is true.</div>
<ng-template #elseBlock>Content to render when condition is false.</ng-template>

Note: Use and implement method 1 because this method fully tested our system.
Thank you 🙂

All methods was sourced from or, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply