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.