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

Having a single quote within a double quote can cause issues with JavaScript code

I am currently developing a Django web app and facing an issue with sending a JSON object to my JavaScript code using a Django template variable. # views.py import json def get_autocomplete_cache(): autocomplete_list = ["test1", "test2", "test3", "te ...

The listview in the Android app is only displayed after it is launched for the second time

My application is designed to retrieve information from a website in JSON format, parse it, store it in an SQLite database, and then display a list of items obtained from the database in a ListView. All functionalities are working correctly except for popu ...

When utilizing JsonConvert, I am unable to obtain any outcomes

I am attempting to convert a JSON stream from an API into an Object. I have also tried converting it into a List, but the result remains the same. Here is a screenshot of the problem: This is the JSON data: [{"time":"1970-01-01T00:00:00.000Z","count" ...

In TypeScript, what specific term denotes a type of data?

Given the following code snippet: class Foo { } interface TypeProvider() { type(): ?; } class Bar implements TypeProvider { type(): ? { return (Foo); } } class Baz implements TypeProvider { type(): ? { return (Bar); ...

Svelte: highlighting input text when selected

Is there a way to select the text of an input element when it is focused using bind:this={ref} and then ref.select()? It seems to only work when I remove the bind:value from the input element. Why is that the case, and how can I solve this issue? Thank yo ...

What is the process of integrating an API key into Apollo-Angular in order to retrieve information from the MongoDB Realm GraphQL API?

I have been utilizing the MongoDB realm GraphQL API to retrieve data, while also using Apollo-Angular. However, in order to access the data through the GraphQL API, an API key is required. I have successfully tested this by using Postman and including the ...

Listening for changes in class property values in TypeScript with Angular involves using the `ngOnChanges`

Back in the days of AngularJS, we could easily listen for variable changes using $watch, $digest... but with the newer versions like Angular 5 and 6, this feature is no longer available. In the current version of Angular, handling variable changes has bec ...

Exploring the process of extracting specific data from a dynamic JSON response and seamlessly transferring it to another request

After receiving a .json file as a response from an API, I need to parse it and extract a specific parameter to pass as input to the next request. How can this be accomplished using Katalon? When attempting to use: response = JSON.parse("response.json"); ...

Utilizing Agora's Screenshare Feature with Angular 8

I am currently working on integrating Agora into my Angular 8 application. So far, I have been able to successfully join and leave video calls. However, I am facing challenges with integrating screen sharing functionality. According to the Agora official d ...

Silencing the warning message from ngrx/router-store about the non-existent feature name 'router'

After adding "@ngrx/router-store" to my project, I noticed that it fills the app console in development mode and unit test results with a repeated message: The warning states that the "router" feature name does not exist in the state. To fix this, make ...

Incorporate @ngx-translate into individual components within Angular 17 for enhanced translation capabilities

I have encountered an issue while using standalone components in Angular 17. Interestingly, when I used module architecture, this problem did not arise. By adding the necessary import to 'AppModule', everything worked perfectly. imports: [ Trans ...

best way to retrieve all rows from ng2-smart table

In my application, I have implemented a smart table component that allows users to input records using default functionalities. Once the user has entered the records into the table, they then need to click on a separate "Save" button (not part of the smart ...

Tips for formatting the key-value pairs in a JSON object

As a newcomer to nodejs, I have managed to successfully retrieve data from the database and display it as a REST API in key/value pairs. The current output appears like this: [{"id":"793","actionname":"test_bsc_interface","actionid":"100"}]. However, I w ...

When attempting to insert a new object in Laravel, the JSON file gets completely replaced

I have a scenario where I need to add a JSON object to an existing JSON file (located in the `storage/app` folder). However, every time I do this, it ends up replacing all the previous data. The code snippet from my controller is as follows: public funct ...

Discovering a way to retrieve objects from an array of objects with matching IDs

Here is a code snippet I put together to illustrate my objective. arr = [ { id:1 , name:'a', title: 'qmummbw' }, { id:2 , name:'b', title: 'sdmus' }, { id:2 , name:'', title: 'dvfv' }, ...

What is the best way to obtain a comprehensive list of nested routes specified in the router configuration?

In my Angular 2 App, I have a dashboard route that contains several child routes. { path: 'app/:property', component: DashboardComponent, canActivate: [AuthGuardService], children: [ { path: 'home', component: HomeComponent } ...

An issue has occurred: changes.forEach does not function as expected

Encountered an issue while attempting to retrieve data from Firestore using Angular/Ionic. PizzaProvider.ts getAllPizzas() { return this._afs.collection<Pizzas>('pizzas', ref => ref); } pizzas-list.ts pizzas: Observable<any[]& ...

Definition in Typescript: The term "value is" refers to a function that takes in any number of arguments of

export function isFunction(value: any): value is (...args: any[]) => any { return typeof value === 'function'; } What is the reason behind using value is (...args: any[]) => any instead of boolean ? ...

Declaring types in NGRX Effect V10 has changed since classes are no longer used, causing types to not be inferred as easily

After the V10 upgrade to NGRX, there seems to be a change where passing a type of Action to the effect is no longer possible. As Actions are now declared as functions instead of classes, I'm wondering if there's still a way to handle this in V10? ...

``Implementing a method to save the output of an asynchronous request in a global variable for future manipulation

It's been a week and I still can't figure this out. Being new to front-end development, I'm struggling with storing the response from subscribe in a global variable for future use. ngOnInit(): void { this.http.get<APIResponse>('ur ...