Retrieving the chosen option from a personalized drop-down element

I have been working on a project using Angular 2, where I created a dropdown component with the following code:

 @Component({
    selector: 'dropdown',
    template: ` <div class="row" >
                    <div class="col-sm-3">
   <select  class="form-control" placeholder="--select--" >
      <option 
        *ngFor="let value of values" (click)="selectItem(value.value)">{{value.text}}</option>
    </select>
</div>
</div>`
})

export class DropdownComponent {
    @Input()
    values: Array<DropdownValue>;

    @Output()
    select: EventEmitter<any>;

    constructor() {
        this.select = new EventEmitter();
        this.values = new Array<DropdownValue>();
    }

    selectItem(value) {
        this.select.emit(value);
    }
}

This dropdown component was then used in another component as shown below:

<dropdown [values]="categories" (select)="onselect($event)"></dropdown>

I encountered an issue while trying to access the selected value from my dropdown list within the component class.

Although using <u><li> for dropdown creation triggers the method onselect(), I preferred creating the dropdown list using <select><option>.... Is there a way to access the selected value through this approach?

 export class AssetComponent
{
    public categories: DropdownValue[] = [
        { "value": 1, "text": "Table" },
        { "value": 2, "text": "Chair" },
        { "value": 3, "text": "Light" }
    ];
    public isCollapsedContent: boolean = false;

    searchfilter(): void {
        this.isCollapsedContent = !this.isCollapsedContent;
        console.log("collapsed happen");
    }
    onselect(value:any): void
    {
        console.log(value)
    }
}

I aim to retrieve the selected dropdown value upon button click:

<button type="button" class="btn btn-primary" (click)="searchfilter()">
    Search here
</button>

Answer №1

To retrieve the selected value, make use of the change event that triggers on the select element:

<select  (change)="onSelect($event.target.value)" class="form-control" placeholder="--select--" >

Pass the selected value to a method and emit it to an @Output property:

onSelect(val) {
    this.select.emit(val)
}

Now you can access the chosen value from the dropdown component:

<dropdown [values]="categories" (select)="onselect($event)"></dropdown>

Remember to import Output from @angular/core and add the output property to your component:

@Output select

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

node-ts displays an error message stating, "Unable to locate the name '__DEV__' (TS2304)."

I recently inserted __DEBUG__ into a TypeScript file within my NodeJS project. Interestingly, in VSCode, no error is displayed. However, upon running the project, I encounter an immediate error: error TS2304: Cannot find name '__DEBUG__'. I att ...

Enable Universal Access to Angular Services in Every Component

Looking for a solution to avoid the need of injecting the SpinnerService class in every component constructor within my Angular app. Any suggestions on streamlining this process? ...

Web-based API for authentication system using Ionic framework and token-based login

https://i.sstatic.net/OzKkI.pngI am developing a photo-sharing app that requires a login system. However, when attempting to log in, an error occurs stating that the value is not found. I am able to retrieve the value in services but struggling to get the ...

Error message shows explicit Typescript type instead of using generic type name

I am looking to use a more explicit name such as userId instead of the type number in my error message for error types. export const primaryKey: PrimaryKey = `CONSUMPTION#123a4`; // The error 'Type ""CONSUMPTION#123a4"" is not assignable to ...

Encountering an error message that reads "State.Push is not a valid function" upon integrating

Currently, I am working on developing a Todo app using react-typescript and redux. During testing, I noticed that the app functions properly without redux-persist, displaying the list of added tasks. However, upon integrating redux-persist, the store does ...

The element is inferred to have an 'any' type due to the fact that a 'string' type expression cannot be used to access elements in the type '{ Categories: Element; Admin: Element; }'

As someone who is new to TypeScript, I am trying to understand why I am encountering a type error in the code below (simplified): "use client"; import { ArrowDownWideNarrow, Settings } from "lucide-react"; interface LinkItemProps { ...

Tips on arranging JSON elements based on the sequence of another JSON

Currently, I am facing a challenge with sorting a list of parks (park_list) based on both distance and area. The code snippet below successfully sorts the list by distance: sortList(index){ return function(a, b){ return (a[index] === b[index] ? 0 : ...

Issues with Formik sign-up

Working on a study project involving React, Typescript, Formik, and Firebase presents a challenge as the code is not functioning correctly. While authentication works well with user creation in Firebase, issues exist with redirection, form clearing, and da ...

Exploring the functionality of typeahead with server-side data integration

I am utilizing ng-select with Angular 7 and creating the following component: export class PostComponent { selectedCategoryID: number; allCategories$: Observable<CategoryModel[]>; constructor(private catService: CategoryService) { } ngOn ...

Conserving node.js native imports for Electron with rollup

I am working on a project using Electron, Svelte, and Typescript. Initially, I used a specific template from here, but it restricted access to node.js built-in imports like fs for security reasons in the browser/electron frontend. However, I do not requir ...

What is the best way to verify if an object is an instance of a particular class using Jasmine testing?

In the process of developing an Angular application, I am currently working on testing a component using this guide. My goal is to ensure that when my ngOnInit() method is called, it correctly initializes my foos property with an array of Foo objects based ...

Using a For Loop in VueJS with TypeScript for an array of objects

I'm currently working on a for loop within an object array. Below is the code snippet I am working with: private async rightsOverview() { let item: any[] = []; const prod = await fetchFromApi<ProductionBaseType>(`/productions/${id ...

What is the process for creating a node module with TypeScript?

So, with regards to the previous question about importing a module using typescript, here is a general answer: 1) Start by creating a blah.d.ts definition file. 2) Use the following code snippet: /// <reference path="./defs/foo/foo.d.ts"/> import ...

Exploring the capabilities of Dynamic Route integration with Server Side components using Supabase in Next.js

export default async function Page({ searchParams, }: { searchParams?: { [key: string]: string | string[] | undefined }; }) { // const searchParams = useSearchParams(); const id = searchParams?.p ?? "aaa"; // default value is "1" ...

Encountered "Function undefined error when invoking within a map in TypeScript"

In my function, there is a map that looks like this: mainFunc(){ // other logics data.map(function (item) { item.number = Math.round(item.number); item.total = item.last - item.first; item.quantity= item?.quantity ? quantityRange(ite ...

Is it possible to utilize the HttpXsrfInterceptor and HttpXsrfCookieExtractor classes for CSRF configuration in Angular 16, despite Intelli-J indicating that they do not exist?

In a valuable article about configuring CSRF for Angular, two options are outlined: First: opt for the default Csrf configuration: providers: [ { provide: HTTP_INTERCEPTORS, useExisting: **HttpXsrfInterceptor**, multi: true } ] Second: If you're usi ...

What strategies can be utilized to manage a sizable data set?

I'm currently tasked with downloading a large dataset from my company's database and analyzing it in Excel. To streamline this process, I am looking to automate it using ExcelOnline. I found a helpful guide at this link provided by Microsoft Powe ...

Could someone clarify for me why I am unable to view the connection status within this code?

Having trouble with the Ionic Network plugin. I've included this code snippet, but it's not functioning as expected. No console logs or error messages are showing up. import { Network } from '@ionic-native/network'; ionViewDidLoad() { ...

Exporting the statement from Ionic 3 page.module.ts file

Recently, I started working on Ionic 3 and decided to implement the new page lazy loading approach. Specifically, I have a page named ControlPage that I am focusing on. In most of the resources I referred to, it was recommended to include the following co ...

A guide on efficiently utilizing combineLatest and mergeMap for handling multiple subscriptions

As I continue to delve into the world of rxjs, I've encountered an issue with managing multiple subscriptions. Specifically, I'm struggling to extract an ID from a response in order to correctly associate photos with products. create(product) { ...