You are not able to use *ngIf nested within *ngFor in Angular 2

I am currently working in Angular2 and trying to bind data from a service. The issue I am facing is that when loading the data, I need to filter it by an ID. Here is what I am trying to achieve:

<md-radio-button
        *ngFor="#item of items_list"
        *ngIf="item.id=1"
        value="{{item.value}}" class="{{item.class}}" checked="{{item.checked}}"> {{item.label}}
</md-radio-button>

Here is the data:

[
  { "id": 1, "value": "Fenêtre" ,"class":"md-primary" ,"label":"Fenêtre" ,"checked":"true"},
  { "id": 2, "value": "Porte Fenêtre" ,"class":"" ,"label":"Porte Fenêtre" }

]

My intention is to only accept data with id = 1, but I am encountering this error:

EXCEPTION: Template parse errors:
Parser Error: Bindings cannot contain assignments at column 14 in [ngIf item.id=1] in RadioFormesType1Component@10:16 ("
        <md-radio-button
                *ngFor="#item of items_list"
                [ERROR ->]*ngIf="item.id=1"
                value="{{item.value}}" class="{{item.class}}" checked="{{item.check"): RadioFormesType1Component@10:16

Does anyone have any suggestions on how to effectively use ngIf and ngFor together?

Answer №1

You have the option to utilize the following:

*ngIf="item.id===1"

instead of using

*ngIf="item.id=1"

Be cautious not to mistakenly assign a value to the id property (using the = operator) instead of checking its value (using either the == or === operators).

Additionally, it is not supported to use ngFor and ngIf on the same element. You could consider implementing it like this:

<div *ngFor="#item of items_list">
  <md-radio-button
      *ngIf="item.id===1"
      value="{{item.value}}" class="{{item.class}}"
      checked="{{item.checked}}">
    {{item.label}}
  </md-radio-button>
</div>

or

<template ngFor #item [ngForOf]="items_list">
  <md-radio-button
      *ngIf="item.id===1"
      value="{{item.value}}" class="{{item.class}}"
      checked="{{item.checked}}">
    {{item.label}}
  </md-radio-button>
</template>

Answer №2

To address this issue, one possible solution is to develop a customized filtering pipe:

import {Pipe} from 'angular2/core';

@Pipe({name: 'filter'})
export class FilterPipe {
  transform(value, filters) {

    var filter = function(obj, filters) {
      return Object.keys(filters).every(prop => obj[prop] === filters[prop])
    }

    return value.filter(obj => filter(obj, filters[0]));
  }
}

To utilize the custom pipe within a component, it can be used in the following manner:

<md-radio-button
  *ngFor="#item of items_list | filter:{id: 1}"
  value="{{item.value}}" class="{{item.class}}" checked="{{item.checked}}"> {{item.label}}
</md-radio-button>

In order for the custom pipe to work effectively, it must be registered within the component:

@Component({
  // ...
  pipes: [FilterPipe]
})

Demonstration: http://plnkr.co/edit/LK5DsaeYnqMdScQw2HGv?p=preview

Answer №3

*ngIf and *ngFor cannot be used together on the same tag. It is necessary to utilize the long form with an explicit <template> tag for one of them.

update

Instead of <template>, consider using <ng-container> which allows for the usage of inline syntax for both *ngIf and *ngFor.

<ng-container *ngFor="#item of items_list">
  <md-radio-button
        *ngIf="item.id=1"
        value="{{item.value}}" class="{{item.class}}" checked="{{item.checked}}"> {{item.label}}
  </md-radio-button>
</ng-container>

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

Incorporate matter-js into your TypeScript project

Upon discovering this file: https://www.npmjs.com/package/@types/matter-js I ran the following line of code: npm install --save @types/matter-js When I tried to use it in the main ts file, an error message appeared: 'Matter' refers to a U ...

Find the identifier that does not currently exist in the collection of objects

There is a situation where I have an array and an object that consists of arrays of ids, which are essentially permission objects. My goal now is to extract the ids that do not exist in the given object. Can someone assist me with devising the necessary l ...

Python JSON schema for extracting parameters

Are you searching for a way to parse requests to a specific URL that come in JSON format, but with varying structures? Some may have timestamps noted as timestamp attribute while others use unixtime, among other variations. The goal is to create JSON schem ...

Sample information in Plain Old Java Object for JSON reference

I am in the process of documenting my JSON API. My API returns Java POJOs that are serialized by Jackson. I am developing a service to provide example JSON for each endpoint. What I want to achieve is similar to the following: class MyPojo { @Example(" ...

Angular does not recognize the boolean variable

Within my Angular component, I have declared two boolean variables: editingPercent: boolean = true; editingCap: boolean = false; In the corresponding HTML file, there is a checkbox that updates these variables based on user input: checkedChanged(e) { ...

How can you loop through an array of objects in TypeScript without relying on the traditional forEach

Currently, I'm working on an array of objects with the following structure. [ { "matListParent": "CH", "dParent": "CUST1", "isAllSelected": true, "childItems&qu ...

Quick data structure for efficient string or JSON retrieval

If I have a large amount of strings, would using a dictionary be the most efficient way to search for them and retrieve their values? When I say large, I mean possibly 2000 strings with each one being 500 characters long (in JSON format). dict1 = {"JSON1" ...

Can a title or custom component be inserted above a nested table in ag-grid?

Currently, I am utilizing ag-grid within an Angular project to display a nested table. However, I am attempting to include a title and button above the child table, which does not seem to be supported by the standard ag-grid documentation. I am open to im ...

The async pipe value seems to be constantly null when dealing with router events

I am facing a straightforward problem while attempting to access an asynchronous property in my template - the returned value is consistently null. This is the method I am using: someAsyncProperty():Observable<string> { return this._router.event ...

Exploring an array within an object using Typescript and React

As a newcomer to TypeScript and React, I have a project where I need to extract data from a JSON file (back-end) and display it on cards (front-end). I am trying to pass props using cards?.items.map, but I'm uncertain about the correct way to access ...

Preventing click propagation for custom react components nested within a MapContainer

I have developed a custom control React component for a map as shown below: export const MapZoom = () => { const map = useMap() const handleButtonClick = () => { map.zoomIn() } return ( <IconButton aria ...

When the keyboard appears, the Ionic 2 form smoothly slides upwards

I am currently working with the most recent version of Ionic 2. In my code, I have a <ion-content padding><form></form></ion-content> containing a text input. However, when attempting to enter text on an Android device, the keyboard ...

Exploring the world of data transfer with Websockets in Flutter

What is the best way to convert JSON data into websocket data in a Flutter application? StreamBuilder( stream: _channel.stream, builder: (context, snapshot) { return ListView.builder( ...

The fix for the unresponsive fixed container in Angular 2 Material

I've encountered an issue with CSS and Angular 2 material. Any element with a fixed position doesn't behave as expected inside an md-sidenav-container. However, when it is placed outside the container, it works perfectly. I have created a Plunker ...

Accessing JSON data in AngularJS from Node.js as the backend and SQL database

I am currently working on a project that involves setting up a node.js server in the backend and using AngularJS in the frontend. In order to fetch information from an SQL database, I have implemented a simple GET request as shown below: req.execute(&apos ...

What could be the reason for a Python library functioning properly when executed from the desktop, but failing to run when invoked from

My web app was running smoothly until I decided to install the jsonpickle library, which caused a problem when calling Python code from PHP. The library functions as expected in the python shell, converting nested structures to JSON data that is too comple ...

Tips for changing the name of a directory in an Angular 6 application

Looking for guidance on renaming a folder in an Angular 6 project's components directory. Is there a safe way to do this without causing any issues, or is it as simple as just changing the name of the folder? Using Visual Studio Code as my IDE. ...

Encountering a 404 error in Angular 9 when refreshing the browser

Encountering a 404 error when attempting to access mysite.com/menu directly, but no issues when navigating through the homepage and selecting the menu option. Tried implementing an .htaccess file following Angular documentation, yet problem persists. Cur ...

Creating dynamic dropdown menus using JSON files in jQuery mobile is a useful technique for enhancing user experience on

I am working with a massive table (8 MBytes) that I need to filter using a small JavaScript application. The process works as follows: Countries Regions Skills I want the user to select one country, one region, and multiple skills as filters. Based on ...

Transferring AgGrid context in a functional React component

I have been working on a component that utilizes AgGrid to display a table, with the data sourced from a Redux selector. My goal is to include a button within a cell in the table that triggers an action based on the specific row's data. However, I a ...