JSON conditional lists

I am attempting to create a dropdown list of "data" depending on the selected "id". The data is retrieved from a JSON response obtained through an HTTP request. Here is the structure:

[
 { "id": 1, "data":[1,2,3,4] },
   { "id": 2, "data":[5,6,7] }
]

The HTML code snippet is as follows:

   <ion-item>
    <ion-label>City</ion-label>
    <ion-select >
      <ion-option *ngFor="let item of receivedData">{{item.name}}</ion-option>
    </ion-select>
  </ion-item>

  <ion-item>
    <ion-label>Fraction</ion-label>
    <ion-select>
      <ion-option [?????] </ion-option>
    </ion-select>
  </ion-item>

The TypeScript (.ts) section is outlined below:

@Component({
  selector: 'page-home',
  templateUrl: 'home.html',
  providers: [PostService]
})
export class HomePage {
  receivedData: Information[];
  
  constructor(public navCtrl: NavController, private service: PostService) {
    this.service.getData('mc').subscribe(data => 
     this.receivedData = data);
  }
}
interface Information {
  id: string;
  data: string[];
}

My aim is to populate a dropdown list based on the selection of "id" in a previous selection. I have attempted using *ngFor but I am having trouble implementing it. As a newcomer to Angular2 and TypeScript, any guidance on how to achieve this would be greatly appreciated.

Thank you!

Answer №1

Here is a sample HTML code snippet for achieving a certain functionality:

    <ion-item>
    <ion-label>City</ion-label>
    <ion-select (change) = "selectId($event)">
      <ion-option *ngFor="let item of items" [value] = "item.id">{{item.name}}</ion-option>
    </ion-select>
  </ion-item>

  <ion-item>
    <ion-label>Fraction</ion-label>
    <ion-select>
      <ion-option *ngFor="let fraction of fractions ">{{fraction}}  </ion-option>
    </ion-select>
  </ion-item>

And here is the corresponding TypeScript code:

    export class HomePage {
      items: Item[];
      fractions:any = [];

      constructor(public navCtrl: NavController, private service: MyService ) {
          this.service.getData().subscribe((data_received) => {
          this.items=data_received;
          this.fractions = data_received[0]['fractions'];
          )};
       }

       selectId(event:any){
           let selectedId = event.target.value;
           for(let i = 0 ; i < this.items.length ; i++){
                if(selectedId === this.items[i]['id']){
                   this.fractions = this.items[i]['data'];
                }
           }

       }

    }
  
    interface Item {
      id: string;
      name: string;
      data: string[];
      fractions: string[];
    }

Answer №2

Hey @vikash, I really appreciate your help. Just made a couple of tweaks to your code and it worked perfectly. Firstly, in Ionic the event is actually called ionChange for that component. Secondly, when iterating through the items in the 'for' loop, the correct length should be length-1. Here's the updated code that does the trick. Thanks again for your input!

<ion-select (ionChange) = "selectId($event)">

In the .ts file:

for (let i=0; i<=this.datosRecibidos.length-1; i++) {

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

Use the any return type instead of unknown for untyped reducers

Currently in the process of refactoring a large redux state, I am facing an issue with reducers that have not yet been converted to typescript which are returning unknown instead of any. Is there a way to modify the default behavior of ReturnType? import ...

Changing Angular Material datepicker format post form submission

After selecting a date, the input field is populated with a format like DD/MM/YYYY Now, when attempting to send this data through a form and logging it in my component, datapicker.component.ts onFindAWhip(form: NgForm){ const value = form.value; ...

Malfunctioning designs arise when Angular-CLI deploys application with webpack

Encountering a strange issue while attempting to run my angular application using angular CLI. Executing ng serve results in the following message post-compilation : A Warning appears... (Emitted value instead of an instance of Error) Cannot find source ...

Unable to get the onchange event to trigger for a span element

Is there a way to trigger the onchange event on a span element that doesn't seem to be working? Here is the code I am using: Attempt 1 document.getElementById(seconds).addEventListener('change', (event: MutationEvent & { path: any }) =& ...

What impact does the Host resolution modifier have on the injection process?

The concept of Hierarchical Dependency Injection in Angular, as explained in the guide here, invites us to view DI as a combined logical tree. Explaining the use of the @Host() modifier, the guide mentions that it restricts the search scope to the <#VI ...

Exploring TypeScript: Navigating the static methods within a generic class

I am trying to work with an abstract class in TypeScript, which includes an enum and a method: export enum SingularPluralForm { SINGULAR, PLURAL }; export abstract class Dog { // ... } Now, I have created a subclass that extends the abstract cla ...

The ngAfterViewChecked function seems to be caught in an endless loop

I am facing an issue where the <cdk-virtual-scroll-viewport> starts from the bottom, but I am unable to scroll up. I suspect that this problem is related to the use of AfterViewChecked. Even after trying AfterViewInit, the issue persists. @ViewChil ...

Clearing out all records from a Firestore collection

I attempted to implement the following method: deleteMessages(){ this.firestore.collection("MESSAGES") .get() .then(res => {res.forEach(element => {element.ref.delete();}); }); } However, I encountered the following err ...

Enclose this within Stencil.js components

Is there a more efficient way to utilize a nested "this" in a Stencil.js component? Currently, I find myself following this approach: render() { let thisNested = this; return <Host> {this.images ? this.imagesArray.map(fu ...

Translation of menu item label has not been executed

Here we have a component called SidebarMenuComponent that is not translating the labels of its menu items correctly. The goal is to get the labels translated, but the current implementation is failing. What is the correct approach to apply translation in t ...

Issue with Angular 10: Modal window fails to open upon second click

Encountering an issue with a Modal window overlapping the navigation bar and overlay due to a third-party bundle.js adding dynamic classes and divs under the parent-container. The problem arises from a fixed positioning of one of the classes which causes t ...

Tips for triggering a function each time a view is shown

I am currently developing an inappbrowser application that involves communication between the webview and the app. Below is a snippet of my code : import { Component } from '@angular/core'; import { NavController, Platform } from 'ionic-an ...

Why does the error message 'unable to locate the Angular project' appear when trying to dockerize an Angular project?

As I try to dockerize my angular app, I encountered a simple example with solutions. However, upon following them, I encountered an error stating 'The serve command requires to be run in an Angular project, but a project definition could not be found. ...

How can I utilize a CDN for JavaScript libraries in Gulp?

As a newcomer to AngularJS and Gulp, I recently encountered an example where certain libraries are copied by Gulp from the 'node_modules' folder into a 'js/lib/angular2' directory: gulp.task('libs', function() { return gulp. ...

Adding or removing an event listener for a document in Angular 2, without using the constructor

In my current project, I implemented a popup component with a movable template feature. The popup opens when the open() method is triggered and attaches movable listeners; then, it closes upon calling the close() method, but the listeners do not get remove ...

Angular MistakeORAngular Error

Every time I refresh the page, I encounter an error in my code while attempting to display a newly edited and saved text. I've initialized the variable, made the access variable public, but it still doesn't work. Can someone point out what I migh ...

Unable to determine the appropriate signature for calling the date function

<td> {{ fundInfo.startDate | date: "yyyy-MM-dd" }} </td> The issue is located in the primeng-test-b.component.html file under src\app\primeng-test-b directory. ...

The launch.json configuration in vscode does not support the use of the property args

I'm currently editing my launch.json file in vscode to make some basic configurations, but I keep encountering an error that says Property args is not allowed. Here is the configuration I have: { "version": "0.2.0", "configurations": [ ...

Exploring the World of Angular6 with the Incredible Power of tinyMCE Editor

Hello, I'm looking to incorporate the tinyMCE editor into my Angular 6 application. I followed a thread that explains how to integrate it, but I ran into an issue where it says the domain is not registered. I would prefer to do this without requiring ...

Expanding and shrinking div elements in Angular with sliding effects on other divs

Hello, I am just starting with angular and angular animations, and I have encountered a problem. Here is the html code that I am working with: <div class="main"> <div class="left" *ngIf="showLeftSide" [@slideInOutLeft]></div> <di ...