Choose the desired option from Angular 7 / Ionic 4 dropdown menu

I am facing an issue with a piece of code that creates dynamic drop-down select options. I need to retrieve the selected values from these items.

The loop in the code generates 3 to 5, or sometimes even more, different dropdowns based on API data.

My goal is to identify which values the user selects and then submit them. However, my "shop now" button is currently non-functional. I have tried various methods but haven't been successful. Can someone help me fix this?

Upon clicking the shop button, I want the value/IDs of the selected items to be printed in the console.

Screenshots are provided for reference, your assistance is greatly appreciated.

https://i.sstatic.net/B2Pao.png https://i.sstatic.net/F5ziY.png

<ion-card>
    <div *ngFor="let item of currentItem.DealRuleDealCode; let i = index">
        <div *ngFor="let CT of item.CategoryType; let j = index ">
            <ion-grid>
                <ion-row padding-left padding-right>
                    <ion-col size="6" no-padding>
                        <ion-label class="catName">{{CT.CategoryName}}: </ion-label>
                    </ion-col>
                    <ion-col>
                        **<ion-select ok-text="Okay" cancel-text="Dismiss" no-padding class="select" (ionChange)="selectChangeHandler($event)">
                            <ion-item *ngFor="let SC of CT.SubCategory; let k = index">
                                <ion-select-option [value]="SC.SubCategoryCode" selected>{{SC.SubCategoryName}} </ion-select-option>
                            </ion-item>
                        </ion-select>**
                    </ion-col>
                </ion-row>
            </ion-grid>
        </div>
    </div>
    <ion-grid>
        <hr />
        <ion-row>

            <ion-col size="6" no-padding>
                <ion-button fill="solid" color="light" expand="full" size="">
                    <label class="bold"> {{currentItem.Price | currency : 'PKR'}} </label>
                </ion-button>
            </ion-col>
            <ion-col size="6" no-padding>
                <ion-button fill="solid" color="light" (click)="shopNow()" expand="full" size="" class="bold">
                    <label> Shop </label>
                    <ion-icon name="add-circle" slot="end">ADD</ion-icon>
                </ion-button>
            </ion-col>
        </ion-row>
    </ion-grid>

</ion-card>

This is my shopNow() function.

I simply need to capture all the selected values within this shopNow() Function. How do I achieve this?

shopNow(){

}

Here is my TypeScript file

import { Component, OnInit, Pipe, PipeTransform, Input } from '@angular/core';
import {Validators, FormBuilder, FormGroup, FormArray} from '@angular/forms';
import { FormsModule, ReactiveFormsModule } from '@angular/forms';

import { ProductsService } from '../services/products.service';
import { Router } from '@angular/router';

@Component({
selector: 'app-menu-detail',
templateUrl: './menu-detail.page.html',
styleUrls: ['./menu-detail.page.scss'],
})

export class MenuDetailPage implements OnInit {

currentItem:[];

selectedValues:[] = [];
//selectedItems = [];

constructor(private productService: ProductsService, private router: Router, private formBuilder: FormBuilder) {}

ngOnInit() {
this.currentItem = this.productService.currentItem;

if(this.currentItem.length < 1){
    this.router.navigate(['main/menu'])
}
}

selectChangeHandler(event){
console.log(event.target.value)
}

shopNow(){

}
}

Answer №1

Your choice is stored within the value:

<ion-select [value]="selectvalues[j]" ok-text="Okay" cancel-text="Dismiss" no-padding class="select" (ionChange)="selectChangeHandler($event)">

It's important to grasp that you are constructing a bi-directional binding system in Angular.

This isn't just about presenting information and collecting it later.

You establish a data model, which is updated in real-time as the user makes selections.

In your code, you will need an array, like I have indicated with selectvalues[], to store the data. It might look something like this:

public selectvalues: any[] = [];

I'm not certain if this alone would be sufficient or if you'll need to add empty elements to match the number of item.CategoryType being displayed. You may need to experiment a bit with this.

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 steps should I take to rectify the errors encountered during the initialization of a fresh Angular project?

Can someone assist me with my updated question? https://i.stack.imgur.com/f8an5.png Click here for the image description. ...

Stop options from being hidden in a select dropdown using HTML

Can I keep the options visible when a user selects an item in the 'select' dropdown? I want to add more options to the 'select' when the user clicks on the 'op2' item, without closing the list of options. <select> <o ...

Creating reusable functions in VueJS that can be accessed globally by all child components

Looking for assistance in setting up a universal function that can be accessed across all my Vue files. For example, when using this code snippet in a Vue file: @click="ModalShow.show('my-create')" I have defined the following constan ...

Guide on incorporating two separate bootstrap themes in a single Angular 7 project

I am working with two modules, Admin and User, each using a different Bootstrap theme - "CoreUI" for admin pages and "Light Bootstrap Dashboard" for user pages. However, when I include all CSS and JS files in the index.html file, there are conflicts betwee ...

When using Ionic, clicking on a Google Maps marker to navigate to another page with NavController can sometimes result in the clicks on the new

Upon successfully displaying the pushed page, I encountered a strange issue where all elements with a (click)='doSomething()' binding stopped working throughout the newly loaded page. Additionally, there was an ion-slides element on the pushed pa ...

Default export in Typescript: React functional component

What is the approach in typescript to achieve this without giving it a name? I know using a name is an option, but that's not what I'm looking for. How can I still utilize the default method? interface IProps { name: string, tag: string, } ...

The most recent Angular application created with Angular-CLI is experiencing issues when compiling the package.json file

I encountered an issue while attempting to create a new Angular application using angular-cli. The problem arises during the npm package installation process. When I try to initiate the creation of a new Angular application with angular-cli and proceed to ...

Using Mat-Error for Two Way Binding leads to frequent triggering of ngModelChange事件

I am working with a mat input field that has two-way data binding using ngModel, and I want to add validation using mat-error and formControl. <mat-form-field [formGroup]="myForm"> <input matInput formControlName="myFormName" autocomplete="off" ...

Ways to retrieve particular items/properties from the JSON response string

Is there a way to extract and display only the first 3 items from my JSON data instead of the entire string? Below is the code I am currently using to loop through and display my records: <tr v-for="(list) in myData" v-bind:key="list.ema ...

Ways to ensure that text wraps to a new line when it exceeds the container's width

I am currently working on implementing a line of text within an ion-card element, but the challenge lies in the fact that the length of the text varies each time. In order to ensure that the entire text is visible and not cut off, especially on devices wit ...

Creating keys from extensive JSON data without having to manually match types using Typescript

Is there a way to efficiently parse and access the values in large JSON files using Typescript, without the need to manually define interfaces for all expected key/value pairs? In the past, working with small JSON files required only extracting a few spec ...

A guide on how to efficiently update and submit a reactive form with a single click of the submit button in Angular

Currently, I have a view component setup where clicking the edit button directs me to the register component for form updates using patchvalue. The issue that I am facing is that when I update and register the form using the same button, it creates anothe ...

Using Typescript, invoke functions within an object by specifying a string key

I am looking for a way to call methods in an Object using string keys, but I'm facing issues with it. Could someone provide some solutions for this? type Methods = { foo?: (v: string) => string; bar?: (v: number) => number; baz?: (v ...

Issue with Font Requests in Browsers when Using Angular 10 and SCSS with @font-face

I have a project built with Angular 10 that utilizes SCSS for styling. In my _typography.scss file, I have defined some @font-face rules pointing to the font files located in the assets/fonts directory. However, when I run the application, the browser does ...

How can one store the value of a promise or observable in an external variable?

I have thoroughly researched the .then() method and comprehend its functionality. In my current project, it is successfully providing me with the desired value. async getDay() { try { let ref = this.db.getDay(this.dateFirebase); ref.then(o ...

Styling your Angular project with CSS

I have a folder called about which contains a file named about.component.css . I want the background-color to be set to aqua only for the page about.component.html. When I try setting the background-color in about.component.css like this: body { backg ...

rxjs subscriptions in Angular

When setting up a subscription in Angular, I am declaring it as follows: counterSubscription: Subscription However, an error is being thrown stating: Property 'counterSubscription' has no initializer and is not definitely assigned in the const ...

Angular 16 SSR encounters a TypeError when the 'instanceof' operator is used on a value that is not an object

I have been facing an issue while updating my Angular application from version 15 to 16. Everything seems to work fine with Angular, including building for Angular Universal without any errors. However, when I attempt to serve using npm run serve:ssr, it t ...

Determining the length of an array of objects nested within another object

I received a response from the API called res. The response is in the following format: {"plan":[{"name":"ABC"},{"name":"DEF"}]}. I am attempting to save this response in my TypeScript code as shown below: ...

Generate a new Map<string, IDoSomethingWith<Something>> instance

Can anyone help me figure out how to instantiate a generic Map using TypeScript? Map<string, IDoSomethingWith<Something>> I attempted the following: const test: ReadonlyArray<string> = ['somekey']; new Map<string, IDoSomet ...