Search code examples
htmlcssangularangular8angular9

Having a dash if field values are null


I am working on an angular application. I have following code in my html

      <div>{{ data.date | date:'d-MMM-y' || '-' }}</div>
       <div>{{ data.id  || '-' }}</div> 

The problem I am facing is, whenever for any field like date and id, if value coming from API is null then next div shifts upward. I want div to be in that particular place it is when value is not null. So, I want to have a dash "-" whenever a value coming from API is null. So in my code I added a || '-' to all the fields but still it is not working. I am not getting "-" in my html. How can I do that?


Solution

  • You were close to the result, you are just missing some parentheses:

    <div>{{ (data?.date) ? (data.date | date:'d-MMM-y') : '-' }}</div>
    

    Working Stackblitz: https://stackblitz.com/edit/angular-vb4peg?file=src/app/app.component.ts

    Just comment the line this.data["date"] = new Date(); and you will see how it changes.