Fetching data from different interfaces with the same name in Angular

In my project, I have two interfaces - one is cropFilter for checkbox filtering and the other is Crop which holds the data.

Let me provide you with the code for better clarity.

1. crop.model.ts

export class Crop { // Interface 1
    name: string;
    district: string;
    subCategory: Subcategory[];
}

export class Subcategory {
    id: number;
    name: string;
   
}

export class CropFilter { // Interface 2
    name: string;
    checked: boolean;

}

2. cropFilter.ts

import { CropFilter } from "./crop.model";


export const CROPSFILTER: CropFilter[] = [
    {
        name: "Rice",
        checked: false
    }, {
        name: "Wheat",
        checked: false
    }, {
        name: "Barley",
        checked: false
    }
]

The above interfaces are used for checkbox filtering.

3. crop.data.ts

import { Crop } from "./crop.model";

export const CROPS: Crop[] = [
    {
        name: "Rice",
        district: "Thane",
        subCategory: [
            {
                id: 1,
                name: "Basmati",
            },
            {
                id: 2,
                name: "Ammamore",
            }
        ]
    },
    {
        name: "Rice",
        district: "Nashik",
        subCategory: [
            {
                id: 1,
                name: "Basmati",
            },
            {
                id: 2,
                name: "Ammamore",
            }
        ]
    },
    {
        name: "Wheat",
        district: "Nashik",
        subCategory: [
            {
                id: 1,
                name: "Durum",
            },
            {
                id: 2,
                name: "Emmer",
            }
        ]
    },
    {
        name: "Barley",
        district: "Ratnagiri",
        subCategory: [
            {
                id: 1,
                name: "Hulless Barley",
            },
            {
                id: 2,
                name: "Barley Flakes",
            }
        ]
    },
    {
        name: "Barley",
        district: "Thane",
        subCategory: [
            {
                id: 1,
                name: "Hulless Barley",
            },
            {
                id: 2,
                name: "Barley Flakes",
                
            }
        ]
    }
];

This data is what I need to fetch from crop.data.ts based on crop.filter.ts

To demonstrate, here is the corresponding HTML part :

1. all-trade.html

<div class="container" *ngIf="crops$ | async">
  <div *ngFor="let item of cropFilterCheckbox$ | async; let i = index">
    <mat-checkbox [checked]="item.checked" (change)="onChange($event, i, item)">
      {{ item.name }}
    </mat-checkbox>
  </div>

  <br />

  <h4>JSON data:</h4>

  <pre>
  {{ cropFilterCheckbox$ | async | json }}
  <div *ngFor="let crop of cropFilterCheckbox$ | async"
  [hidden]="!crop.checked"
  >{{ crop.name }}
  
</div>
<button type="button" class="btn">Basic</button>
</pre>
</div>

2. crop.service.ts

import { Injectable } from "@angular/core";

import { Observable, of } from "rxjs";

import { Crop, CropFilter, DistrictFilter } from "../shared/crop.model";
import { CROPS } from "../shared/crop.data";
import { CROPSFILTER } from '../shared/cropFilter';

@Injectable({
  providedIn: "root"
})
export class CropService {
  constructor() { }

  crops: Crop[] = CROPS;
  cropFilterCheckbox: CropFilter[] = CROPSFILTER;

  getAllCrops(): Observable<Crop[]> {
    return of(this.crops);
  }

  getCropFilter(): Observable<CropFilter[]> {
    return of(this.cropFilterCheckbox)
  }

  
  getCrop(name: string): Observable<any> {
    const crop = this.crops.filter(crop => crop.name === name)[0];

    return of(crop);
  }
}

You can view the final output https://i.sstatic.net/SeWeD.png.

Please provide guidance on how to fetch data from crop.data.ts based on crop.filter.ts. For instance, when a user checks the Rice checkbox, all details of Rice from crop.data.ts should be fetched and displayed on the screen.

Answer №1

When the checkbox is changed, implement an event handler as shown below. Keep track of which checkboxes the user has selected in a variable called "AppliedFilter" and then pass that array list to your service method.

handleCheckboxChange(status, name) {
    if (status && this.appliedFilter.indexOf(name) === -1) {
        this.appliedFilter.push(name);
    } else {
        this.appliedFilter = this.appliedFilter.filter((x) => x !== name);
    }
    this.updatedCropsList = this.cropService.updateCropsList(this.appliedFilter);
}

In your service method, filter your records based on the array like this:

updateCropsList(names: string[]): Observable<any> {
    const updatedCrops = this.crops.filter((crop) => names.includes(crop.name));
    return of(updatedCrops);
}

Check out the working example on CodeSandbox:

https://codesandbox.io/s/filter-data-x2p0w?file=/src/app/app.component.ts:289-294

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

What is the best way to simulate fetch in Redux Async Actions?

When writing tests in the Redux Writing Tests section, how does store.dispatch(actions.fetchTodos()) not trigger the fetch method when store.dispatch is directly calling actions.fetchTodos? The issue arises when trying to run similar code and encountering ...

Head to the "/unauthorised" route in Angular while maintaining the current URL intact

I have a security guard that directs the user to an "/unauthorised" route when they do not have permission to access the current page (which could be any page). @Injectable() export class PermissionGuard implements CanActivate { constructor(private reado ...

Having trouble with the yAxis in HighCharts on Angular 8? FireFox and IE causing issues?

Hey there! Currently, I am using "highcharts 8.0.0" along with "highcharts-angular 2.4.0" in combination with Angular 8. While the line charts are displaying perfectly fine on Google Chrome, I seem to be facing an issue with Firefox. The problem is that t ...

Manipulating State in React: How to add a property to an object within an array within a component's state

Currently, I am retrieving an array of objects stored in the state, and I am attempting to include a new property to each of these objects. However, I am encountering a problem where even though I can see the new property being added to each object, when ...

Looking to display an alert message upon scrolling down a specific division element in HTML

In the midst of the body tag, I have a div element. <div id="place"> </div> I'm trying to achieve a scenario where upon scrolling down and encountering the div with the ID "place", an alert is displayed. My current approach involves che ...

What are the steps to implement localStorage in Vuejs3?

I'm feeling a bit lost when it comes to localStorage and its usage. I have a component called Statistic.vue which displays a modal at the end. Statistic.vue <template> <p class='modal'>{{numberOfGames}}</p> </template& ...

Explaining the process of defining `this.props` and storing data in the global Redux state

I am currently diving into the world of react and Redux and I'm using a react project on GitHub called overcode/rovercode-ui as a learning tool for understanding react and Redux. As I explore this project, I have come across some intriguing questions. ...

Getting a Node Express 404 error while attempting to display an image that was uploaded using multer

I am facing an issue with uploading images using multer. Previously, everything was working perfectly fine on localhost. The images were getting uploaded and I could view them using the provided URL link in the code. However, after uploading it to a server ...

Locate and modify a single item in a list using NGRX

I have an array of items stored in my ngrx/store. When the user clicks on a button, I need to retrieve a specific item based on its id and update its properties without using ngxr/entities. I have managed to achieve this functionality in my current imple ...

Change the default values for grid column configurations in Ext JS globally

The Ext.grid.column.Column class contains the following configurations: draggable (Default: true) sortable (Default: true) menuDisabled (Default: false) Is there a way to globally change the default values of these configurations for all grid columns i ...

Obscured painting surface appearance using Three.js

I am attempting to incorporate a blurred texture into my Three.js scene, but the results are not what I expected. Canvas: var c = document.getElementById("myCanvas"); var context1 = c.getContext("2d"); context1.filter = "blur(16px)"; context1.beginPath( ...

Retrieving the total count of data entries from the JSON server endpoint

Working on a practice application with the JSON server serving as the backend, I have a question. Is there a way to determine the total number of records at an endpoint without actually loading all the records? For example, if my db.json file contains da ...

The error message in TypeScript is indicating that the property 'x' is not found in the type '{}', which is required for a computed key

Description of a Typescript fragment: enum Field { age, bugs, } interface Foo { number_age: number; number_bugs: number; } function createFoo():Foo { let obj = {}; let index = 0; for (let key in Field) { obj['numb ...

Steps for verifying the existence of a value within an array in relation to another object and generating a new object based on the result

Within my coding realm, I possess an array const dataCheck = ["Rohit", "Ravi"]; In addition to this first array, I also have a secondary array filled with objects const userData = [ { name: "Sagar" }, { name: "V ...

There seems to be an issue with the rangeslider.js jQuery plugin not being recognized as a function within the project. However, there are

I am currently working on integrating a Range-slider into my Django project with the help of rangeslider.js. I was able to successfully create a functional example on Codepen at https://codepen.io/Slurpgoose/pen/GRRpmpX, and everything seemed to be running ...

What is the best way to select types conditionally based on the presence of a property in another type?

To begin with, I have a specific desired outcome: type Wrapper<ID extends string> = { id: ID }; type WrapperWithPayload<ID extends string, Payload> = { id: ID, payload: Payload }; enum IDs { FOO = "ID Foo", BAR = "ID Bar", BAZ = "ID Baz ...

Utilizing the NPM package as a JSX Component is prohibited due to type errors

I've been encountering some unusual type errors in my TypeScript project with certain packages. For example: 'TimeAgo' cannot be used as a JSX component. Its instance type 'ReactTimeago<keyof IntrinsicElements | ComponentType<{} ...

The error message "Express Routing - Attempting to access property 'include' of undefined" is displayed when an

I am attempting to implement basic routing based on the user's selections on the first page. If the user picks 2 out of 3 options on the parent page, I want them to only see those two child pages and not the third. My strategy for the parent page was ...

A Promise-based value returned by a Typescript decorator with universal methods

I am currently working on creating a method decorator that can be applied to both prototype and instance methods. Referenced from: Typescript decorators not working with arrow functions In the code provided below, the instanceMethod() is returning a Prom ...

Querying for the presence of an ObjectId in an array in Mongoose

I'm developing a Node.js project that involves two models: User and Project. Below is the Schema for the Project model: const ProjectSchema = new mongoose.Schema({ name: { type: String, maxlength: 50, required: true, } ...