What causes *ngIf to display blank boxes and what is the solution to resolve this problem?

I am currently working on an HTML project where I need to display objects from an array using Angular. My goal is to only show the objects in the array that are not empty. While I have managed to hide the content of empty objects, the boxes holding this content still appear. I would appreciate any assistance in fixing this issue.

HTML:

<div class=content>
 <div class=data-item *ngFor="let item of dataSource">
  <div *ngIf="item.Value != ''" >
   <div>{{item.Header}}</div>
   <div>{{item.Value}}</div>
  </div>
 </div>
</div>

CSS:

.content {
width: 100%;
display: flex;
flex-wrap: wrap;
}
.data-item{
flex: 0 0 21%;
border-style: solid;
}

TS:

import { Component, VERSION } from '@angular/core';

@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: [ './app.component.css' ]
})
export class AppComponent  {
  name = 'Angular ' + VERSION.major;

  dataSource: items[] = [
    {Header: 'Header A1', Value: 123},
    {Header: 'Header B2', Value: 234},
    {Header: 'Header C3', Value: ''},
    {Header: 'Header D4', Value: 456},
    {Header: 'Header E5', Value: ''},
    {Header: 'Header F6', Value: 678},
    {Header: 'Header G7', Value: 789},
  ]
}

export interface items{
  Header: string;
  Value: any;
}

Check out the screenshot of the final rendered HTML: Rendered HTML

Answer №1

To eliminate the need for an extra div, utilize ng-container and apply a CSS class to the original div used with *ngIf

Sample HTML

<div class=content>
<ng-container  *ngFor="let item of dataSource">
 <div *ngIf="item.Value != ''" class=data-item>
  <div>{{item.Header}}</div>
  <div>{{item.Value}}</div>
 </div>
</ng-container>
</div>

Check out this stackblitz example

Answer №2

The issue lies in your *ngFor's creation of the item.

You can't use an *ngIf to prevent the display of these items because an element cannot have both attributes simultaneously.

To resolve this dilemma, you must narrow down dataSource to include only the desired items for display.

There are several methods to achieve this, but I recommend utilizing a pipe.

@Pipe({
  name: 'filterOutEmptyData',
})
export class FilterOutEmptyDataPipe implements PipeTransform {
  transform(
    input: items[]
  ): items[] {
    return input?.filter(item => item.Value !== '');
  }
}

After that, in your HTML template,

<div class=data-item *ngFor="let item of (dataSource | filterOutEmptyData)">

Remember to include the pipe in your module as well.

Answer №3

Give this a try:

<div class=container>
  <ng-container *ngFor="let entry of dataCollection">
    <div class="data-entry" *ngIf="!!entry.value">
       <div>{{entry.title}}</div>
       <div>{{entry.value}}</div>
    </div>
  </ng-container>
</div>

To clarify, make sure the condition is applied to the actual box element and not just its contents as seen in your original code.

Also, take advantage of ngContainer which does not render any extra elements, to simplify the looping process.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Testing the Binding of Models in Angular 5 Using Jasmine Framework

I'm currently working on writing a unit test to verify that the JSON data returned from the components method call successfully links to a TypeScript model. Here's what my model looks like: export interface IPlayerAccount { playerId: number; ...

Interacting with local data using Express server

I am currently in the process of developing a web application for my web art class using Node.js with npm and Express. The concept behind the site is to have the entire body colored in one solid color, but allow users to text a hexcode/CSS color to a Twili ...

Hide the menu when a menu link is selected

After conducting extensive research, I have come across several scripts that can achieve what I am trying to do. However, I am unsure of how to implement them with my particular WordPress theme. Therefore, I am seeking assistance here: The theme I am usin ...

Share your Angular Elements web component as an npm module

Is there a way to package an Angular app as an npm module, especially when it is wrapped as a web component using Angular Elements? I'm interested in seamlessly importing the web component into another application through npm, rather than manually inc ...

Next.js v13 and Firebase are encountering a CORS policy error which is blocking access to the site.webmanifest file

Background: I am currently developing a website using Next.js version 13 in combination with Firebase, and I have successfully deployed it on Vercel. Upon inspecting the console, I came across two CORS policy errors specifically related to my site.webmani ...

Tips for determining what elements are being updated in terms of style

I need assistance with modifying the functionality of a webpage's dropdown menu. Currently, it displays when the mouse hovers over it, but I want to change it to appear on click using my own JavaScript. Despite setting the onmouseout and onmouseover e ...

Using the HTML form element to achieve two-way binding on array elements

I am working with an array of objects within a component that will be iterated in the template. app.component.ts import {Component, OnInit} from '@angular/core'; @Component({ selector: 'app-root', templateUrl: './app.compone ...

Different CSS values can be applied for specific versions of Internet Explorer by using conditional comments

I am dealing with a CSS class named "myclass" that requires a z-index of 5 specifically for IE8. I have attempted to achieve this using the following methods: .myclass{ z-index: 5\9; } ---> Interestingly, this method applies from IE10 onwards and ...

Separate the iframe sessions

I am working with 6 iframes from the same domain but with different URLs and subdirectories. Each iframe sets a cookie with the same name but a different value using the HTML header "set-cookie". To prevent interference between these cookies, I need to fin ...

Using a foreach loop to showcase information within elements, specifically for JSON with several arrays

I am working with JSON data from an external domain to create a list of posts by extracting and displaying the necessary information. { "dati": [ { "id": 98762, "tipo": "eventi", "titolo": “TITOLO ...

I am currently attempting to create a JavaScript function that searches for the <td> elements within an HTML table. However, the function fails to work properly when there are <th></th> tags included

UPDATE: Scratch that, I managed to solve my issue by creating a separate table for the header to contain all of my <th> tags I am working with an HTML table and I would like to add a search bar to filter through the content since it is quite large. ...

The table headers in the second table do not match the queryAllSelector

I've encountered an issue with my JavaScript snippet that displays a responsive table. When I use the snippet for a second table with the same class, the formatting gets messed up on mobile devices (try resizing your screen to see). It seems like the ...

Having trouble with running the command ng update -g @angular/cli, receiving an error message

When running the command ng update -g @angular/cli I encountered the following issue: Unexpectedly, an error occurred stating package amcharts3-angular2 has no version null while trying to execute the ng update -g @angular/cli command. ...

converting an entire HTML layout into a PDF using JavaScript

I am attempting to convert an HTML design to PDF using the following script: <script src="https://cdnjs.cloudflare.com/ajax/libs/jspdf/1.3.3/jspdf.min.js"></script>. I have designed a table to my liking, here is how it looks in HTML: https://i. ...

GSAP also brings scale transformations to life through its animation capabilities

I have an SVG graphic and I'm looking to make four elements appear in place. I've been using GSAP, but the elements seem to be flying into place rather than scaling up. Here's the code snippet I've been using: gsap.fromTo( ...

What is the method for displaying the delete icon, a child component located within the Menu Item, upon hovering over it using Material UI CSS syntax?

My goal is to display the delete icon when hovering over a specific menu item that is being mapped using the map function. The desired functionality is for the delete icon to appear on the corresponding menu item when it is hovered over. I attempted to i ...

Seeking guidance on utilizing JavaScript for implementing an onclick event

I am exploring the realm of Event tracking with Google Analytics. To make this happen, I know that I must include an onclick attribute to select links (those specifically requested for tracking) in the following manner: <a href="http://www.example.com" ...

Angular: Refresh Mat-Table data following any changes

I'm currently working with a Mat-table that has expandable rows, each containing an update functionality for the data. While the POST and GET requests are functioning properly, I encounter an issue where I need to reload the page in order to see the u ...

Identify when a click occurs outside specific elements

I've been searching for solutions to address this issue, but so far nothing has worked. Here is the JavaScript code I am using: var specifiedElement = document.getElementById('a'); document.addEventListener('click', function(eve ...

What could be causing my page width to only expand to 100% when using "fit-content"?

After searching extensively, I'm unable to find a solution that fits my current issue. My goal is to construct a practice ecommerce website using React. One of the components I have is a header which I'd like to occupy 100% of the screen width, c ...