I am excited to create a Dynamic Routing system that selects specific elements from an array of objects using Typescript

1. crops-list.component.ts

import { Component, OnInit } from '@angular/core';
import { ActivatedRoute } from '@angular/router';

@Component({
  selector: 'app-crops-list',
  templateUrl: './crops-list.component.html',
  styleUrls: ['./crops-list.component.css'],
})
export class CropsListComponent implements OnInit {

// Array of Objects for different crops

  crops = [
    {
      name: 'Rice',
      checked: true,
      subCategory: [
        {
          id: 1,
          name: 'Basmati',
          isActive: true,
        },
        {
          id: 2,
          name: 'Ammamore',
          isActive: true,
        },
      ],
    },
    {
      name: 'Wheat',
      checked: true,
      subCategory: [
        {
          id: 1,
          name: 'Durum',
          isActive: true,
        },
        {
          id: 2,
          name: 'Emmer',
          isActive: true,
        },
      ],
    }, {
      name: 'Barley',
      checked: true,
      subCategory: [
        {
          id: 1,
          name: 'Hulless Barley',
          isActive: true,
        },
        {
          id: 2,
          name: 'Barley Flakes',
          isActive: true,
        },
      ],
    }
  ]

  onChange(event, index, item) {
    item.checked = !item.checked;
    console.log(index, event, item);
  }

  constructor(private route: ActivatedRoute) { }

  ngOnInit(): void { }

  
}

2. crops-list.component.html

<app-header></app-header>
<div
  fxLayout="row"
  fxLayout.lt-md="column"
  fxLayoutAlign="space-between start"
  fxLayoutAlign.lt-md="start stretch"
>
  <div class="container-outer" fxFlex="20">
    <div class="filters">
      <section class="example-section">
        <span class="example-list-section">
          <h1>Select Crop</h1>
        </span>
        <span class="example-list-section">
          <ul>
            <li *ngFor="let crop of crops">
              <mat-checkbox
                [checked]="crop.checked"
                (change)="onChange($event, i, crop)"
              >
                {{ crop.name }}
              </mat-checkbox>
            </li>
          </ul>
        </span>
      </section>

      <section class="example-section">
        <span class="example-list-section">
          <h1>Select District</h1>
        </span>
        <span class="example-list-section">
          <ul>
            <li *ngFor="let district of districts">
              <mat-checkbox>
                {{ district.name }}
              </mat-checkbox>
            </li>
          </ul>
        </span>
      </section>
    </div>
  </div>
  <div class="content container-outer" fxFlex="80">
    <mat-card
      class="crop-card"
      style="min-width: 17%"
      *ngFor="let crop of crops"
      [hidden]="!crop.checked"
    >
    
      <a
        [routerLink]="['/crops', crop.id]"
        routerLinkActive="router-link-active"
      >
        <mat-card-header>
          <img
            mat-card-avatar
            class="example-header-image"
            src="/assets/icons/crops/{{ crop.name }}.PNG"
            alt="crop-image"
          />
          <mat-card-title>{{ crop.name }}</mat-card-title>
          <mat-card-subtitle>100 Kgs</mat-card-subtitle>
        </mat-card-header>
      </a>
      
      <mat-card-content>
        <p>PRICE</p>
      </mat-card-content>
    </mat-card>
  </div>
</div>

<app-footer></app-footer>

https://i.sstatic.net/Df7iT.png

On the webpage, there are cards like "RICE", "WHEAT", and "BARLY". Clicking on each card should navigate to a different component page and display the name of the corresponding subcategory from the Array of Objects. For example, clicking on the "Wheat" card should navigate to a different page and display the names of subcategories of Wheat section. Example: When I click on the Wheat Card it should navigate to a different page and display the name of subCategory of Wheat section.

crops = [
    {
      name: 'Rice', <---- 1. Go here
      checked: true,
      subCategory: [ <-- 2. Go to subCategory and fetch the name of "RICE" on a different Page
        {
          id: 1,
          name: 'Basmati',
          isActive: true,
        },
        {
          id: 2,
          name: 'Ammamore',
          isActive: true,
        },
      ],
    },
    {
      name: 'Wheat',
      checked: true,
      subCategory: [
        {
          id: 1,
          name: 'Durum',
          isActive: true,
        },
        {
          id: 2,
          name: 'Emmer',
          isActive: true,
        },
      ],
    }, {
      name: 'Barley',
      checked: true,
      subCategory: [
        {
          id: 1,
          name: 'Hulless Barley',
          isActive: true,
        },
        {
          id: 2,
          name: 'Barley Flakes',
          isActive: true,
        },
      ],
    }
  ]

Answer №1

Utilize a BehaviorSubject for similar functionality

In app-routing.component.ts, define the route path

 const routes: Routes = [
 //other routes
 { path:'crop/:name', component:CropComponent}
 ]
 

In crop.ts, model the interface for crop

export class Crop{
  name: string;
  checked: boolean;
  subCategory:Subcategory[];

}

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

In service.ts, create a subject and define getter and setter methods

export class CropService {
private selectedCrop= new BehaviorSubject<Crop>(null);

setCrop(crop:Crop){
 this.selectedCrop.next(crop);
 }

getCrop(){
return this.selectedCrop.asObservable().pipe(skipWhile(val=> val === null)); 
}

}

In all-trades.component.html, replace the routerLink with click event

<mat-card
  class="crop-card"
  style="min-width: 17%"
  *ngFor="let crop of crops"
  [hidden]="!crop.checked"
>

  <a
   (click)="onSelect(crop)"
    routerLinkActive="router-link-active"
  >
    <mat-card-header>
      <img
        mat-card-avatar
        class="example-header-image"
        src="/assets/icons/crops/{{ crop.name }}.PNG"
        alt="crop-image"
      />
      <mat-card-title>{{ crop.name }}</mat-card-title>
      <mat-card-subtitle>100 Kgs</mat-card-subtitle>
    </mat-card-header>
  </a>
  <mat-card-content>
    <p>PRICE</p>
  </mat-card-content>
</mat-card>

In all-trades.component.ts, emit the selected crop and route to the same component

constructor(private service: Cropservice, private router:Router){}

onSelect(selectedCrop:Crop){
this.service.setCrop(selectedCrop);
this.router.navigateByUrl(`crop/${crop.name}`);
}

In crop.component.ts, subscribe to the subject and store the crop data locally

crop: Crop
export class CropComponent implements OnInit{

ngOnInit(){
this.service.getCrop().subscribe((selectedCrop:Crop)=>this.crop = 
selectedCrop)
}
}

In crop.component.html

<div *ngFor="let category of crop.subCategory">{{category.id}}</div>

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

Uninterrupted movement within a picture carousel

Seeking a way to create a smooth transition in an image slider with sliding dividers using continuous switching when clicking previous/next buttons. Currently, the dividers replace each other from far positions. Any ideas on achieving a seamless single mov ...

Unique styling implementation for element situated underneath Angular 6 router-outlet

I'm currently working on implementing router transitions in my Angular application, and I've encountered an unusual problem. The styling for the router-outlet element is being applied to the element that comes after it in the DOM hierarchy. Here ...

Automatic playback of the next video in a video slider

Looking to upgrade my video slider functionality - switching between videos, playing automatically when one finishes. Struggling to find a solution that combines manual control with automatic playback. My attempt: function videoUrl(hmmmmmm){ ...

How can I implement SSO and Auth for multiple sub-domains using PHP?

Is it possible to implement SSO using PHP between two different sub-domains (e.g. parappawithfries.com and *.parappawithfries.com)? My current configuration is causing issues as I use Cloudflare to direct my subs to a different 000webhost website. While I ...

JavaScript Regular Expression for separating a collection of email addresses into individual parts

I am very close to getting this to work, but not quite there yet. In my JavaScript code, I have a string with a list of email addresses, each formatted differently: var emailList = '<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data- ...

Vue.js seems to be leading me down a long and steady path of progress at a snail

I've exhausted all efforts to resolve the file paths for Home and App. I even turned to AI to help me out, but still no luck. Code snippet from main.js in the src folder: import Home from '@views/Home.vue'; // Using alias import App from ...

Beta 8 of Angular Material 2 is causing MdDialog.afterAllClosed to return an undefined result instead of the expected data

I am currently facing an issue where the result from the dialog component's close method is returning as undefined. Could this be a bug present in angular material 2 beta 8? I have searched extensively online but have not been able to find any inform ...

Error: excessive recursion detected in <div ng-view="" class="ng-scope">

I've recently started learning angularJS and I've encountered an error that I need help with. Below is my index.html file: <body ng-app="myApp"> <div ng-view></div> <a href="table">click</a> <script ...

Is Angular CLI incorrectly flagging circular dependencies for nested Material Dialogs?

My Angular 8 project incorporates a service class that manages the creation of dialog components using Angular Material. These dialogs are based on different component types, and the service class is designed to handle their rendering. Below is a simplifie ...

Employing a lexicon of hexadecimal color code values to harmonize CSS styles

I have a unique requirement where I need to utilize a dictionary of HTML color codes and then apply those colors as styles. It's an interesting challenge! Here is an example of how my color dictionary looks like: const colorCodes = { red: ...

What causes npm start to fail in Angular 6 after incorporating social login functionality?

I am currently working on integrating Social Login functionality into my app. I have attempted to incorporate the following: npm install --save angular-6-social-login-fixed npm install --save angular-6-social-login npm install --save angular-6-social-log ...

Modifying ngModel will result in the corresponding ngModel in another Angular2 browser being updated

I'm a novice when it comes to Angular 2 and I'm currently working on a project using npm to run the application. At the moment, I have it hosted on localhost with port 3000. The issue I'm facing in my project is that when I open the same ...

Despite encountering the 'property x does not exist on type y' error for Mongoose, it continues to function properly

When working with Mongoose, I encountered the error TS2339: Property 'highTemp' does not exist on type 'Location' when using dot notation (model.attribute). Interestingly, the code still functions as intended. I found a solution in the ...

What is the best way to add animation to my `<div>` elements when my website is first loaded?

I am looking for a way to enhance the appearance of my <div> contents when my website loads. They should gradually appear one after the other as the website loads. Additionally, the background image should load slowly due to being filtered by the wea ...

The session in Express.js is not retained across different domains

I am currently developing a third-party application that will be utilized across multiple domains. My main goal is to manage a session per user who uses the app, which led me to implement the express-session module for this purpose. However, I encountered ...

Retrieving an HTML page from one location and automatically populating textboxes with preexisting values on the receiving end

I'm currently facing a dilemma. Here's the issue: I need to load an HTML page (let's call it test.html) when a button is clicked on another page (referred to as home page). The test.html page has input boxes that I want to populate with p ...

Create a word filter that doesn't conceal the words

I have a code snippet that filters a JSON object based on name and title. I also have an array of specific words and I would like to modify the filter to highlight those words in the text without hiding them. $scope.arrayFilter=["bad,bill,mikle,awesome,mo ...

Uncovering the enum object value by passing a key in typescript/javascript

How can I retrieve the value of an enum object by passing the key in typescript? The switch case method works, but what if the enum object is too long? Is there a better way to achieve this? export enum AllGroup = { 'GROUP_AUS': 'A' &a ...

Passing HTML content to an ng-bootstrap modal in Angular 2+

My modal setup in the Component Library looks like this. Keep in mind, I am working within a Component Library, not just the application. Within my Component Library... The template is as follows: <div class="modal-header"> <h4 class="mt- ...

Load jQuery DataTable when the event changes

I have implemented a script that loads the DataTable when the page is ready: function initializeDataTable(serviceUrl) { var $dataTable = $('#example1').DataTable({ "ajax": serviceUrl, "iDisplayLength": 25, "order": [[2, "asc"]], ...