Showing container element only if certain condition is met but display the children in Angular 2+

I am looking to create a grid-style view for a list of Angular components, where I can display up to 4 components in each row.

The question that comes close to what I need is the following: Angular 2 NgIf, dont render container element on condition but show its child elements

However, this solution only works when the container has one child. Here is my initial attempt (I understand that an else case could be used):

<ng-container *ngFor="let pair of responsePair; let i = index">
  <ng-container *ngIf="i % 4 == 0">
    <div class="row">
      <app-report-tile></app-report-tile>
    </div>
  </ng-container>

  <ng-container *ngIf="i % 4 != 0">
    <app-report-tile></app-report-tile>
  </ng-container>
</ng-container> 

Currently, the row container is only printed for every 4th element, whereas I need the next 3 child components to also belong to this row container.

Is there a way to conditionally not render an HTML element?

Answer №1

After carefully reviewing your specifications:

Check out the code on stackblitz

This is the HTML structure:

<ng-container *ngFor="let pair of responsePair; let i = index">
    <div *ngIf="i % 4 == 0" class="row">
        <div class="col">
            <hello></hello>
        </div>
        <div class="col">
            <hello></hello>
        </div>
        <div class="col">
            <hello></hello>
        </div>
        <div class="col">
            <hello></hello>
        </div>
    </div>
</ng-container>

Answer №2

UnluckyAj sparked my inspiration, leading me to discover the solution on my own. I streamlined the process by creating a single row and preloading the subsequent elements:

<ng-container *ngFor="let pair of responsePair; let i = index">
  <ng-container *ngIf="i % 4 == 0">
    <div class="row">
      <app-report-tile *ngIf="responsePair[i] !== undefined" [data]="responsePair[i]"></app-report-tile>
      <app-report-tile *ngIf="responsePair[i + 1] !== undefined" [data]="responsePair[i + 1]"></app-report-tile>
      <app-report-tile *ngIf="responsePair[i + 2] !== undefined" [data]="responsePair[i + 2]"></app-report-tile>
      <app-report-tile *ngIf="responsePair[i + 3] !== undefined" [data]="responsePair[i + 3]"></app-report-tile>
    </div>
  </ng-container>
</ng-container>

It's important to include *ngIf directives for each component to prevent any potential exceptions.

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

Encountering issues when launching Node.js application using PM2 and ts-node in production mode

I've run into an issue while trying to use PM2 with ts-node. Whenever I attempt to start my application using PM2, I receive an error message stating that the ts-node interpreter is not found in the PATH. I've experimented with installing ts-nod ...

Ensure that the input field consistently shows numbers with exactly two decimal places

Below is an input field that I want to always display the input value with 2 decimal places. For example, if I input 1, it should show as 1.00 in the input field. How can this be achieved using formControl since ngModel is not being used? Thank you. I att ...

Display spinner exclusively for prolonged requests using Angular's HttpInterceptor

I developed a custom interceptor that displays a spinner whenever an HTTP request is initiated: import { HttpEvent, HttpHandler, HttpInterceptor, HttpRequest } from '@angular/common/http'; import { Injectable } from '@angular/core'; im ...

Issue with Loosing Focus in React TextInput when typing the letter "S"

My TextInput is acting strangely - it loses focus only when I type the letter s. All other letters work fine. <FormControl key={"1"} sx={{ m: 1 }} variant="outlined" onChange={handleFilterValueChange}> <InputLabel htmlFor=& ...

Problem encountered with ESLint when utilizing babel module-resolver in conjunction with TypeScript

Typescript is not making type inferences with resolved imports, but it does with relative imports. Any assistance would be greatly appreciated. https://i.sstatic.net/2pgHX.png When using the 'useTheme' function, an error is displayed: "U ...

How can one store the value of a promise or observable in an external variable?

I have thoroughly researched the .then() method and comprehend its functionality. In my current project, it is successfully providing me with the desired value. async getDay() { try { let ref = this.db.getDay(this.dateFirebase); ref.then(o ...

Encountering an unexpected token error while trying to compile a Typescript file to Javascript, even though it had previously worked

In my Typescript project, I usually run it using "ts-node". $ ts-node .\src\index.ts it works =) However, I wanted to compile it to Javascript, so I tried the following: $ tsc $ node .\src\index.js Unfortunately, I encountered the f ...

Angular JSON converter - Transform XML data to JSON format

Struggling to convert XML API response to JSON using xml2js library, facing issues with getting 'undefined' in the console. Here is my API service: export class WordgameService { public apiUrl = "http://www.wordgamedictionary.com/api/v1/reference ...

Angular universal issue: 404 error code failing to function properly

After numerous attempts, I find myself at a dead end. Our Angular 11 website requires Universal for SEO purposes, and we have set up a 404 page to redirect when necessary. The issue arises when the redirect returns a status code of 200 instead of 404. To ...

What is the process to verify a password?

Hey everyone! I've successfully implemented control forms in my login.component.ts for handling email and password input. Now, I want to add these controls to my register.component.ts as well. Specifically, how can I implement controls for the passwor ...

A simple trick to compile and run TypeScript files with just one command!

Converting TS to JS is typically done using the tsc command, followed by executing the resulting .js file with node. This process involves two steps but is necessary to run a .ts file successfully. I'm curious, though, if there is a way to streamlin ...

Is it possible for a lambda in TypeScript to have access to the class scope but return undefined

In my TypeScript code, I have a class used as a Pipe in Angular 2 to render markdown. It compiles successfully but encounters a runtime exception on a specific line: var Remarkable = require('remarkable'); @Pipe({ name: 'markdown' ...

What could be causing React to generate an error when attempting to utilize my custom hook to retrieve data from Firebase using context?

Currently, I am restructuring my code to improve organization by moving data fetching to custom hooks instead of within the component file. However, I am encountering issues with the hook not functioning properly when used in conjunction with my context. ...

Comparing RxJS and Async/Await: Which one is the better choice?

As an Angular/Ionic developer, I recently encountered challenges with the Async/Await pattern, prompting me to reconsider my approach. A colleague suggested using the RxJS library to handle asynchronous calls more effectively, so I delved into exploring al ...

Leveraging a React hook within a Next.js API route

I am looking for a way to expose the data fetched by a React.js hook as a REST endpoint using Next.js. To create a REST endpoint in Next.js, I can easily use the code below in pages/api/index.tsx export default function handler(req: NextApiRequest, res: N ...

How can I change the CSS class of my navbar component in Angular 2 from a different component?

Here is a custom progress bar component I created: @Component ({ selector: 'progress-bar', templateUrl: './progress-bar.component.html', styleUrls: ['./progress-bar.component.css'] }) export class ProgressBarComponent ...

Getter and setter methods in Angular Typescript are returning undefined values

I am facing a challenge in my Angular project where I need a property within a class to return specific fields in an object. Although I have implemented this successfully in .Net before, I am encountering an issue with getting an "Undefined" value returned ...

Before the user closes the window, Angular 2 makes an HTTP request

Whenever the user is about to close the window, I want to ensure that changes are saved. However, I'm facing an issue where the changes are not saved when I close the tab, even though it works fine when I refresh the page with F5. Below is the canDeac ...

Tips for incorporating the Sanitize library into Angular 6:

What is the most effective library for sanitization in Angular 6 to enhance security measures? Since injecting dependencies can be tricky, what are some recommended methods for implementing this in an Angular 6 project? ...

Analyzing the type of object properties from a different perspective

I am new to TypeScript and have encountered many similar questions. I was able to find a solution, but I'm not sure if it's the most efficient one. When constructing the target object as {obj: someObject, prop: "objectPropName"}, I pas ...