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

Is it possible to adjust the vertical background-position independently?

While creating a navigation bar using the <ul> element, I have come up with the following CSS code: .nav { list-style: none; background: url(/images/nav.png) no-repeat; width: 666px; height: 60px; } .nav li { font-size: 0px; backgr ...

What is the best way to maintain a socket.io ID while navigating through dynamic HTML files?

Utilizing express and node for server hosting, socket io is employed to track users by saving their unique socket.id. There are two pages in the webapp - a login page and a content page. app.get("/", function(req, res) { res.sendFile(__dirname + "/log ...

Include the button beneath the Rating section using JQuery or AJAX

I am having trouble adding buttons after the result.date in my code. Placing the buttons between td tags is causing an [object Object] error to show up. $.ajax({ type: 'GET', url: 'someUrl.php', data: {op : "demo"}, da ...

using an array as an argument in the filtering function

Is there a way to pass an array to the filter method in JavaScript? I have successfully filtered an array using another array. However, my filter array currently has a global scope. How can I pass the array to make my code cleaner? var array = [1, 2, 3, ...

Add option button

Is there a way to dynamically add radio buttons using jQuery or JavaScript and save the data into a database? I have successfully appended input types such as text, textarea, checkbox, and select with options. Here is my code: <!DOCTYPE html> < ...

The horizontal navigation bar will not extend the entire length of the page

I'm facing an issue with my horizontal navigation bar as it doesn't span the entire screen. I need help figuring out how to make it full-width. You can see what I mean here. Additionally, once the navigation bar spans the screen, I want the image ...

Converting base64 dataUrls into images using typescript

When using ng2-image cropper, it does not accept the "src" attribute and instead requires the "image" attribute. As a result, if a dataUrl is provided, the image will not display in the cropper. I am utilizing the camera to capture an image and obtaining ...

Creating a Masonry Slider with varying heights and widths of images is a simple and effective way to showcase diverse content in a visually

I am looking to implement a unique grid image slider that accommodates images of varying heights and widths. I envision something similar to the example shown below. The image showcases a pattern where the sliders alternate between square images and two r ...

Guide: Positioning the Icon in the Top Right Corner of the Image

Objective: The goal is to ensure that the expand icon is always at the upper right corner of the image, regardless of its size or the responsive design in place. Challenge: I have attempted to address this issue but have unfortunately been unsuccessfu ...

Starting a new subscription once the current one expires

What is the process for starting a new subscription once an existing one ends using rxjs operators in Angular with 2 select statements? this.store.pipe( takeUntil(this.onDestroy$), select(getDatasetIsCreation), filter((datasetCreation) ...

Updating a div's border using JavaScript

I recently generated a div element dynamically through code. var Element; Element = document.createElement('div'); My goal now is to modify the right and bottom borders to "#CCCCCC 1px solid". I aim to achieve this without relying on any exte ...

The object's key values were unexpectedly empty despite containing data

There's an issue with my object - it initially gets key values, but then suddenly loses them all. All the key values become empty and a message appears in the console for the object: "this value was evaluated upon first expanding. it may have ch ...

Sliding a div out from the right using jQuery

I am attempting to create a sliding effect from the right on a div using jQuery. I have managed to accomplish part of it, but not exactly as I would like. You can view my code on this JSFiddle. While the div slides out smoothly, the text inside wraps when ...

Challenges with locating text within the innerHtml property of a VB WebBrowser Object

Using Visual Studio 2010 with Visual Basic.NET In my project, I have created a form that utilizes a WebBrowser control to load an HTML file. Users are able to search for specific words or phrases within the document, prompting me to extract the innerHtml ...

"Exploring the methods to retrieve Firebase authentication error details and outputting the console log message along with

When I encounter an error in Firebase authentication, I want to display it in the console log. However, nothing is being logged and the catch block is not even getting executed. I am unsure about why this is happening and how to retrieve the error code and ...

Ensure that clicking on various links will result in them opening in a new pop-up window consistently

I am facing an issue with my HTML page where I have Four Links that are supposed to open in separate new windows, each displaying unique content. For instance: Link1 should open in Window 1, Link2 in Window 2, and so on... The problem I'm encounter ...

Executing a Parent Function from a Child Component in Angular 11

I have successfully passed values between Angular components using Input/Output several times before, but I am currently facing a unique situation for which I cannot find a solution: There are two components involved: home.component (parent component) T ...

How to Connect to Printer in Ionic 2

Does anyone know if there is an option to implement printing/connecting a printer from Ionic 2? Is there a Cordova plugin available for printing? I found this plugin: Cordova Print plugin Any help/information on this would be greatly appreciated. Also, i ...

The Component Spec (Karma) is failing to call the Angular Mock Service

Struggling to write test cases for mainchat.component.ts as a beginner in Karma. See the sample code below: getActiveUsers(): void { this._ChatService.getActiveUserInfo().subscribe(data => { this.Users = data; }, err => ...

Issues with Formik sign-up

Working on a study project involving React, Typescript, Formik, and Firebase presents a challenge as the code is not functioning correctly. While authentication works well with user creation in Firebase, issues exist with redirection, form clearing, and da ...