Angular: Show empty content if *ngIf condition is not met

Having trouble with displaying subitems of an array using two different arrays. The issue arises when the condition fails, resulting in empty whitespace being printed and occupying unnecessary space under each card header. I've tried using ng-template but still facing the same problem.

Here's the code snippet:

HTML

<div *ngIf = "containsData">
    <div class="card-body">
      <div style = "width: 70%; margin: auto;" *ngFor = "let data of cardCheckArray; let i = index">
        <div class="card-header">
          <p>{{data}}</p>
        </div>
        <div class="card-body" *ngFor = "let data2 of fetchedData">
          <div *ngIf = "data2.PROCESS_NAME == data; else printNothing">
            <p>{{data2.DOCUMENT_NAME}}</p>
            <p>{{data2.DATE_SUBMITTED | date: 'medium'}}</p>
            <p>{{data2.PROCESS_NAME}}</p>
          </div>
          <ng-template #printNothing>
            <p>empty</p>
          </ng-template>
        </div>
      </div>

      <hr>
    </div>
  </div>

typescript

var swap = this.fetchedData[0].PROCESS_NAME;

      for (var x in this.fetchedData)
      {
        if(swap == this.fetchedData[x].PROCESS_NAME)
        {
          continue;
        }
        else
        {
          this.cardCheckArray.push(swap);
          swap = this.fetchedData[x].PROCESS_NAME;
        }
      }
this.cardCheckArray.push(swap);

Looking for a solution to avoid printing empty whitespace when the *ngIf condition fails. Any help would be much appreciated. Thank you!

Answer №1

In Angular, the ngFor directive is used to render multiple elements inside a div. However, if you need to use both the ngFor and ngIf directives on the same element, you can utilize an ng-container. This special element allows you to apply structural directives (such as ngFor) without rendering any extra HTML code. Simply place your div with the card-body class inside the ng-container, and then add the ngIf directive to control its visibility.

Answer №2

To optimize your code, consider using ng-container instead of *ngFor along with avoiding the use of else and ng-template.

<ng-container "let data2 of fetchedData" >
  &lt;div class="card-body" *ngIf = "data2.PROCESS_NAME == data; else printNothing">
     …

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

Tips for effectively navigating with the `Next-intl` and `next/link` componentsWhen working with the

I have implemented a next-intl library to enable multi-language support on my website. This means that the paths for different languages look like www.next.com/de or www.next.com/en Currently, I am utilizing NextJS 14. <NextLink href="/support-us& ...

Determine the datatype of an object within another object, even when the datatype of the object might not be

Here is the structure I am working with: type MyType = { a?: { b: number; } } I am trying to access the type of b. After that, my goal is to create a new type based on this: type AnotherType = { mytype: MyType['a']['b'] } ...

Set the variable value by clicking on another component within *ngFor in Angular 2

I am attempting to use *ngFor to pass an object to another component, but only the last object in the table is being passed. The object that was clicked should be displayed instead. How can I solve this issue? <tr data-toggle="control-sidebar" *ngFor=" ...

Get rid of the Modal simply by clicking on the X mark

Objective: The modal should only be closed by clicking the X mark and not by clicking outside of it. Challenge: I am unsure how to resolve this issue when using the syntax code [config]="{backdrop: 'static'}" Additional Information: I am new ...

Guide to releasing a React component utilizing TypeScript

I am in the process of publishing a React component that I have developed with Typescript, and I have some uncertainties about the best approach to take. This is the structure of my workspace: ./src index.tsx styles.module.css logo.svg Subcomp ...

Is it better for a component's render function to have a return type of React.ReactNode or JSX.Element?

While both options do not produce compilation errors, is there a difference between the two and is one more preferable than the other? ...

Exploring the depths of nested collections in Angular 12

As I work on my very first Angular/Firestore app, I find myself grappling with understanding how to retrieve data from nested collections. The Firestore database path that I need to access is as follows: /Customer(CollectionName)/cl0Apvalb6c0w9hltQ8AOTF4go ...

Strategies for sorting through numerous characteristics of a hierarchical array that may stretch across multiple levels of the tree

In order to simplify the process, I am looking for a way to filter multiple properties of a parent-child array that may have multiple levels. This is specifically for an Open Source datagrid library that is utilized by hundreds of users. The array consist ...

Using an Angular variable with routerLink functionality

Is there a way to concatenate an id in my routerLink? <a routerLink="['/details', {{data.id}}]"> </a> is not working for me. Any suggestions on how to achieve this? Thank you in advance ...

Update of Angular Material Table rows triggers a popup, however only the values from the first array are populated in all edited rows

Developed an application with two components (A & B) that includes a popup dialog for editing: Component A fetches the data from a service and loads it into a data table Component B initializes the data when a pop event is triggered from A. Usually, ...

The TypeScript reflection system is unable to deduce the GraphQL type in this case. To resolve this issue, it is necessary to explicitly specify the type for the 'id' property of the 'Address'

import { ObjectType, ID, Int, Field } from 'type-graphql'; @ObjectType() export default class Address { @Field(type => ID) id: String; @Field() type: string; @Field() title: string; @Field() location: string; } More informa ...

TS2322 error: Attempting to assign type 'any' to type 'never' is invalid

Currently, I am utilizing "typescript"- "3.8.3", and "mongoose": "5.9.11". Previously, my code was functional with version "typescript": "3.4.x", and "mongoose": "4.x". Here is a snippet of my code: https://i.stack.imgur.com/j3Ko2.png The definition for ...

What are some strategies for achieving more specific type inference for deeply nested object properties?

Here's a sample of a schema library I'm currently developing (</pre> The main idea behind this library is to handle table schemas that include columns referencing other table schemas. The objective is to create a function that accepts two ...

Exploring Google Places with Angular 2, Typescript, and Ionic 2

Has anyone successfully transformed this code into TypeScript? var map; var infowindow; function initMap() { var pyrmont = {lat: -33.867, lng: 151.195}; map = new google.maps.Map(document.getElementById('map'), { center: py ...

Having trouble with npm i after installing the newest versions of node and npm

I recently upgraded my node and npm to the latest versions. However, my ionic 3 project (version 3.9.2) is now encountering issues when I run npm i. Strangely, this problem only occurs with this specific project and not with new projects. Any help in resol ...

Moving an object in threeJS from one location to another, from point A to point

i stumbled upon some questions on SO, but I'm still struggling to figure out how to create a basic animation like the ones I saw. Essentially, all I want to do is move an object from point A to point B. I've tried using translate, but the object ...

What is the reason for the Quokka's absence from the Array?

I'm encountering an issue where Quokka is not displaying the result for this specific line of code: [...Array(max - min + 1).keys()].map(i => i + min); Here's a screenshot for reference: https://i.sstatic.net/3NmVA.png Can someone identify wh ...

I am encountering an issue where my application is not recognizing the angular material/dialog module. What steps can I take to resolve this issue and ensure that it functions properly?

For my Angular application, I am trying to incorporate two Material UI components - MatDialog and MatDialogConfig. However, it seems like there might be an issue with the placement of these modules as all other modules are functioning correctly except fo ...

Unable to retrieve a string from one function within another function

Three functions are responsible for triggering POST API calls, with the intention of returning a success or failure message to whoever invokes them (Observable<string>). In an effort to avoid repetition, I introduced a new function to retrieve succe ...

Filtering out specific properties from an element within a JavaScript forEach loop

const findBloodType = bloodCodeArray.find(bloodCode => bloodCode.code.toUpperCase() === bloodType.toUpperCase()).code; In my Angular code, I am trying to retrieve just the 'code' property of the 'bloodCode' element using a callback ...