Exploring the Potential of Using ngIf-else Expressions in Angular 2

Here is a code snippet that I wrote:

<tr *ngFor="let sample of data; let i = index" [attr.data-index]="i">
    <ng-container *ngIf="sample.configuration_type == 1; then thenBlock; else elseBlock"></ng-container>
       <ng-template #thenBlock>
           <td>{{sample.item_number}}</td>
           <td>{{sample.make}}</td>
           <td>{{sample.model}}</td>
       </ng-template>
       <ng-template #elseBlock>
           <td>{{sample.serial_number}}</td>
           <td>{{sample.capacity}}</td>
           <td>{{sample.model}}</td>
       </ng-template>
</tr>

I encountered an error while trying to display it:

An issue occurred with binding 'ngIfThen' as it is not recognized as a valid property of 'ng-container'. 1. If 'ng-container' is an Angular component and has 'ngIfThen' input, ensure it belongs to the current module. 2. For Web Components, add "CUSTOM_ELEMENTS_SCHEMA" to '@NgModule.schemas' to prevent this message. ("gFor="let sample of data; let i = index" [attr.data-index]="i")

Answer №1

When encountering this error, remember that using ngFor and ngIf on the same tag is not allowed. Instead, utilize ng-container in the following manner:

<tr *ngFor="let sample of data; let i = index" [attr.data-index]="i">
    <ng-container *ngIf="sample.configuration_type === 1">
        <td>{{sample.item_number}}</td>
        <td>{{sample.make}}</td>
        <td>{{sample.model}}</td>
        <td>{{bucket.class}}</td>
        <td>{{bucket.capacity}}</td>
    </ng-container>
</tr>

Answer №2

Prior to utilizing any structural directives, make sure to import the CommonModule from @angular/common into your module. As a reminder, ngIfElse functionality is only accessible starting from version 4.0.0.

For the revised question: You have the option to utilize ngIf along with the else syntax to distinguish between different items.

Include this code snippet within your tr element:

<ng-container *ngIf="sample.configuration_type === 1; else elseBlock">
    <td>{{sample.item_number}}</td>
    <td>{{sample.make}}</td>
    <td>{{sample.model}}</td>
</ng-container>
<ng-template #elseBlock>
    <td>{{sample.serial_number}}</td>
    <td>{{sample.capacity}}</td>
    <td>{{sample.model}}</td>
</ng-template>

If you prefer using ng-template exclusively, consider implementing this code:

<ng-template [ngIf]="sample.configuration_type === 1" [ngIfElse]="elseBlock">
    <td>{{sample.item_number}}</td>
    <td>{{sample.make}}</td>
    <td>{{sample.model}}</td>
</ng-template>
<ng-template #elseBlock>
    <td>{{sample.serial_number}}</td>
    <td>{{sample.capacity}}</td>
    <td>{{sample.model}}</td>
</ng-template>

For more detailed information on structural directives, visit the angular official documentation page.

Note: This answer was initially provided for the original question before it was modified by the OP to serve another purpose.

To filter the data within your component, you can use methods like the array filter method.

Here's an example:

export class MyComponent {
    // ...
    public get filteredData() {
       return this.data.filter(sample => sample.configuration_type !== 1);
    }
    // ...
}

Then, in your component, utilize the filteredData property for looping purposes:

<tr *ngFor="let sample of filteredData; let i = index" [attr.data-index]="i">
    <td>{{sample.item_number}}</td>
    <td>{{sample.make}}</td>
    <td>{{sample.model}}</td>
    <td>{{bucket.class}}</td>
    <td>{{bucket.capacity}}</td>
</tr>

Answer №3

Ensure that the CommonModule has been correctly imported into your AppModule imports.

import {CommonModule} from '@angular/common';

@NgModule({

  imports: [
    // ... other modules    
    CommonModule
  ],

To see a demonstration of the if-then-else behavior, check out this Plunker link: PLUNKER DEMO

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 React Context malfunctioning due to a syntax error?

Using the function "login" from React context is causing an error for me: const handleLogin = async (data: LoginType) => { try { await login(auth, data.email, data.password); router.push("/Dashboard"); } catch (error: an ...

A tutorial on setting a component path as the main URL in Angular 6

I am working on an Angular 6 application that has multiple page routes. My goal is to set the home component as the root URL so that when the application initially serves (ng serve -o), instead of landing on localhost:4200, which is currently just a blank ...

Issues occurred when attempting to access information with postgres and nodeJS

Below is the configuration I have set up in my files: const express = require('express') const app = express() const port = 8000 const expense_model = require('./expense_model') app.use(express.json()); app.us ...

Remove all `Function.prototype` methods from Typescript

Can a callable object (function) be created without utilizing Function.prototype methods? let callableObject = () => 'foo' callableObject.bar = 'baz' callableObject() // 'foo' callableObject // {bar: 'baz'} call ...

Tips for determining the datatype of a callback parameter based on the specified event name

Let's say we have the following code snippet: type eventType = "ready" | "buzz"; type eventTypeReadyInput = {appIsReady: string}; interface mysdk { on:(event: eventType, cb: (input: eventTypeCallbackInput) => void) => void } mysdk.on("ready", ...

Learn how to utilize the "is" status in Postma within your code, even when this particular status is not included in the response

Service.ts Upon invoking this function, I receive a JSON response similar to the following: public signupuser(user: Users): Observable<boolean> { let headers = new Headers(); headers.append('Content-Type', 'application/json&a ...

What is the trick to make the "@" alias function in a Typescript ESM project?

My current challenge involves running a script using ESM: ts-node --esm -r tsconfig-paths/register -T src/server/api/jobs/index.ts Despite my efforts, the script seems unable to handle imports like import '@/server/init.ts': CustomError: Cannot ...

Drop and drag the spotlight

On my website, I am looking to implement a feature that will make it easier for users to identify the drag and drop area. I found a code snippet on JSFIDDLE that works perfectly there. However, when I tried to use it on my local server, it doesn't se ...

Switch back and forth between two different function loops by clicking

I have implemented two sets of functions that animate an SVG: one set runs in a vertical loop (Rightscale.verticalUp and Rightscale.verticalDown) and the other in a horizontal loop (Rightscale.horizontalUp or Rightscale.horizontalDown). On clicking the SVG ...

Received an unexpected GET request while attempting to modify an HTML attribute

After clicking a button in my HTML file, a function is called from a separate file. Here is the code for that function: function getRandomVideoLink(){ //AJAX request to /random-video console.log("ajax request"); var xhttp = new XMLHttpRequest( ...

Creating dynamic values in data-tables using Vuetify

As I work with JSON data, my current task involves formatting it using Vuetify's Data Tables. The official documentation provides guidance on defining table headers as shown below: import data from './data.json' export default { data ...

Ways to update state based on changes in localStorage values

Is there a way to update the state when the value of localStorage changes? For instance, I have a language switch button for French and English. When I click on English, it gets stored in localStorage. How can I ensure that the entire project switches to t ...

How can I use jQuery to add styling to my menu options?

Looking to customize my menu items: <ul> <li class="static"> <a class="static menu-item" href="/mySites/AboutUs">About Us</a> </li> <li class="static"> <a class="static-menu-item" href="/m ...

Sending information to a subpage through props using a query in the URL triggers a 431 Request Header Fields Too Large error

I have a page called campaigns, and I am facing an issue on the index page where I want to pass data to my dynamic page [campaignId].tsx. Although I can see the data on my dynamic page, the URL links are becoming too long, leading to an HTTP Status code 4 ...

The Next.js developer encounters an issue where the build fails due to a ReferenceError on a client component, stating that "window

Just starting out with nextjs, I'm sticking to using only the basic features without diving into any advanced functionalities. During the next build process, I encountered an issue where 6 paths failed because of a ReferenceError: window is not defin ...

"Troubleshooting: Handling null values in a web service when using jQuery

The API located at http://localhost:57501/api/addDatabase contains the following code snippet: [System.Web.Mvc.HttpPost] public ActionResult Post(addDatabase pNuevaConeccion) { pNuevaConeccion.insertarMetaData(); return null; ...

Angular Dependency Injection: Individual instances of each service are provided for every module usage

Within my application, there is a module called "FileUpload". The upload service included is "UploadService", which receives a service injection with the interface "RequestService." I also have two other modules: FileManager1 and FileManager2. Each file m ...

Having trouble with clearInterval in React TypeScript?

I have been encountering issues with the clearInterval function in TypeScript for React. I am not sure why the interval is not being cleared. To address this problem, I defined a variable let interval_counter;, and used it as follows: interval_counter = ...

Verify whether a class or id is present in the HTML response obtained from an AJAX request

Is there a way to check the content of HTML returned by an AJAX call before rendering it to avoid any flickering effect? I am aware of using hasClass() to check for classes, but in this scenario, the AJAX response is returning HTML. I can append the HTML ...

The error message "TypeError: Unable to access the 'getFullWidth' property of an undefined value when using TSLint and TypeScript" was

I have been using Dan Wahlin's tutorials and online examples to set up Gulp and Typescript, but I am facing an issue with the tslint() function. The problem occurs in my code as follows: node_modules\tslint\lib\language\walker&bso ...