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

Retrieve Django imagefield file name using jQuery before submitting

Exploring the essential Django image file upload procedure, where the image model incorporates the ImageField class. There's a custom display button replacing the default upload button which usually showcases the image name alongside it. Hence, the ne ...

"Troubleshooting Problems with Scaling in the jQuery Mouse Wheel Plugin

I am currently utilizing this code in conjunction with the following plugin: mouse wheel $('#painter').on('mousewheel', function(e) { cp.scale(2, 2); var e0 = e.originalEvent, delta = e0.wheelDelta || -e0.de ...

The interface does not allow properties to be assigned as string indexes

Below are the interfaces I am currently working with: export interface Meta { counter: number; limit: number; offset: number; total: number; } export interface Api<T> { [key: string]: T[]; meta: Meta; // encountered an error here } I h ...

Passing an object in Vue.js during a redirect

i currently have two components named projectListComponent and projectSingleComponent. I want to pass an object from component 1 to component 2 during redirection. Here is my code: projectListComponent.vue <template> <div class="row justify ...

Setting a default action for an Ext.Ajax.request error situation

In my application, I frequently make ajax requests using the Ext.Ajax.request method. Often, I find myself skipping error handling for failed requests due to time constraints or lack of interest in implementing fancy error handling. As a result, my code us ...

Elevate with Ease: Tailwind's Height Transition

I've been attempting to implement a transition effect using TailwindCSS, but I haven't found an updated version with the latest features. Here's the code snippet: <div id="fadeInElement" className={visible ? " w-2/3 px-5 t ...

Guidelines for simulating ActivatedRouteSnapshot in observable testing situations

I am currently testing an observable feature from a service in Angular. This particular observable will output a boolean value based on the queryParam provided. For effective testing of this observable, it is essential to mock the queryParam value. Howev ...

Challenge in backward compatibility when converting from .on() to .live()

Struggling to make hammer.js work with an outdated 1.6 jQuery in my CMS. The function "on()" isn't available, so I have to use "live()". Here are the two instances: 1. var hammertime = new Hammer(element[0], { drag_lock_to_axis: true }); hammertime. ...

The parameters for Vue.js @change events are consistently returning as 0 whenever a file is uploaded by clicking on the picture

Check out my JSFiddle here:: https://jsfiddle.net/includephone/o9gpb1q8 I've encountered an issue involving the @change event on an input field. My goal is to create a carousel of images with 4 images per slide. Data Object Structure data: functio ...

Utilizing hooks in node.js functions

Is there a way to apply before and after hooks on a function? I need these hooks to trigger whenever the function is called. While Express.js middleware concept works for routes, I require similar hooks for functions on the server side. function main(){ ...

I seem to be having trouble locating the correct file location

Apologies for the simplicity of my question. I've been struggling to include the find.js file in my articles.js file. Despite trying multiple variations, I can't seem to get the pathname right and haven't found a solution online. Can someon ...

leveraging angular service with ionic framework

(function () { 'use strict'; angular .module('app') .factory('UserService', UserService); UserService.$inject = ['$http']; function UserService($http) { var service = {}; ...

Setting the paths property in a project with multiple tsconfig.json files: a step-by-step guide

My file structure is organized as follows: |__ app1/ | |__ tsconfig.json |__ utilities/ | |__ files.ts |__ base-tsconfig.json I have defined the paths property in base-tsconfig.json like this: "compilerOptions": { "baseUrl": ".", "pa ...

What is the reason for the lack of an applied CSS selector?

.colored p{ color: red; } article > .colored{ color:powderblue; } .blue{ color: white; } <!DOCTYPE html> <html lang="ko"> <head> <meta charset="UTF-8> <meta name="viewport" content="width=device-width, initi ...

Controlling user login sessions and cookies with angular.js is essential for ensuring secure and seamless

I have a login application where I need to implement session and cookies using angular.js. Below is the code for my login functionality. loginController.js: var loginAdmin=angular.module('Channabasavashwara'); loginAdmin.controller('log ...

Angular 6 - Resolving the Issue of 'Function calls are not supported in decorators' in Production Builds

Currently, I'm in the process of developing a cutting-edge Angular 6 application. However, as I was progressing with the development phase and tried to create a prod build using the following command: ng build --prod To my dismay, I encountered a pe ...

Leveraging jQuery's Append functionality

Struggling with using jQuery's .append() method. Check out my code: $('#all ul li').each(function() { if ($(this).children('.material-icons').hasClass('offline-icon') == false) { $('#online ul').append ...

What is the proper way to use Object.entries with my specific type?

On my form, I have three fields (sku, sku_variation, name) that I want to use for creating a new product. I thought of converting the parsedData to unknown first, but it seems like a bad practice. export type TProduct = { id: string, sku: number ...

Module request: How can I save the gathered cookies as a variable?

library: https://www.npmjs.com/package/request I am attempting to simultaneously log in with multiple accounts on a website. To manage each session effectively, I plan to create an object where I will store the cookies associated with each account. Now, ...

Is that possible to prevent the use of the & symbol in Angular 4 HTTP requests?

Using an HTTP request to save data in my database. The code snippet I used is: const form = '&inputdata=' + myinput + '&rf_date=' + rf_date; return this.http.post(this.rootUrl, form, {headers : this.reqHeader}); In thi ...