Struggling to retrieve an Object from an HTMLSelectElement within an Angular project

Can you help me with this code snippet:

<select #categorySelect (change)="goToCategory.emit(categorySelect.value)" style="...">
    <option selected hidden>All</option>    
    <option 
        [ngValue]="category" 
        *ngFor="let category of categories">
            {{category.groupName}}
        </option>
</select>
@Output() goToCategory = new EventEmitter<Category>();

I am facing an issue where I am getting the string 'object Object' instead of the actual object category. Is there a way to modify the code so that I can get the object element for the function in '(change)'?

Answer №1

Consider implementing a method within the component to emit the object value instead of doing it directly from the template:

Here's a suggestion:

Create a new helper method called getCategory, where you can set the category.id as an option value for easy reference later:

<select #categorySelect (change)="getCategory(categorySelect.value)" style="...">


[value]="category.id" 

Add a new method that locates the object and emits it from there:

  getCategory(id:string) {
    
    const categorySelect = this.categories.find(el=>el.id === id);

    this.goToCategory.emit(categorySelect);
  }

You may also want to utilize ngModel:

<select [(ngModel)]="categorySelect" (change)="goToCategory.emit(categorySelect)" style="...">
// need to tweak default selected..
categorySelect:Category= this.categories[0]; // or 'All'

Answer №2

To make your category object usable in a select, it needs to be serialized into a string value. Here's how you can do it:

[ngValue]="JSON.stringify(category)"

When you need to access the category data (for example, in the method triggered by your Output), simply deserialize the string back into an object like this:

handleSerializedCategory(serializedCategory:string){    
let category = JSON.parse(serializedCategory) as Category;

//Perform actions on the category object
}

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

JavaScript causing values to disappear when the page refreshes

When a user hovers over ImageButtons, I use Javascript to change the ImageUrl. However, on submitting the form, the updated ImageUrl property is not reflected in the code behind. Similarly, I also dynamically update a span tag using Javascript, but its alt ...

Add delayed event listeners to embedded AJAX request beyond function boundaries

I'm working on developing a custom AJAX method extension named getApi that automatically includes my authentication bearer token in the request header. In my code, there is a function called getToken() which retrieves the token either from sessionSto ...

Having trouble arranging the elements when swapping within a pop-up modal

When I drag and drop two divs inside a modal popup, their positions shift down during the animation. I am struggling to fix this issue. HTML Code: <title> Tile Swapping with Animation</title> <body> <button type="button" class=" ...

The collapsible section expands upon loading the page

Trying to implement Disqus as a plugin on my test webpage, I created a collapsible section with a "Show comments" button. The idea was to hide the plugin by default and reveal it only when users click on "Show comments". Despite using the w3schools example ...

What strategies can be used to ensure that the page layout adjusts seamlessly to even the smallest shifts in window size?

Of course, I am familiar with media queries and how they allow us to set specific min-width and max-width ranges for CSS changes. However, when I look at the website styledotme.com, I notice that the block/div beneath the navigation bar gradually shrinks ...

The toArray function in MongoDB does not support the use of Array push

I'm attempting to loop through all documents within collections, store them in a global variable, but it seems like the push() function is not working and returning an empty array [] inside of toArray(). Any ideas? const mongo = require('mongodb ...

How to filter out content not contained within a specific form tag using Javascript

One feature of my webpage displays restaurant reviews, each with a like button. However, the issue arises when submitting the like form: everything within and outside of a particular form tag gets sent to the back-end. This makes it challenging to determin ...

Looking for guidance on utilizing pushState and handling onpopstate events?

By using ajax, I am able to load specific page content without refreshing the entire page. In order to make the back button functionality work, I utilize pushState and onpopstate as shown below: function get_page(args){ .... $.ajax({ url ...

Using Vue with Firebase to fetch a specific range of data starting from a particular record and ending at the

I am looking to retrieve all records from a certain record to the very last one in my database. ref.orderByChild("date").equalTo("19/11/2020 @ 19:50:29").on("child_added", (snapshot) => { console.log(snapshot.va ...

AngularJS: Controller causing an unchecked error

I'm a beginner to AngularJS and I'm struggling to understand why I'm not getting a response when clicking the button. Any help would be greatly appreciated. I've reviewed other examples of controllers being used but I can't seem to ...

Divergent find function behavior in jQuery when applied to div or tbody

I've encountered an issue while using the jQuery find selector by Id with a div and tbody. Let me simplify my problem for better understanding. HTML <div id='iamdiv'>HELLO</div> <table> <tbody id='iamtbody' ...

What is the procedure for implementing a RoleGuard in Angular 6?

Is there a way to retrieve the user role from the token? I've managed to fetch the token using the decoding feature of angular2-jwt, but when I try to apply it for accessing the admin route, it returns a value of false. Upon checking with console.lo ...

Mysterious anomaly observed: Peculiar trajectory detected in canvas image during left

I have a fascinating HTML5 Canvas that showcases the movement of two identical objects to both the right and the left. Although the right side operates flawlessly, I've noticed that the left object leaves behind an intriguing trail with a hint of gree ...

Eliminate any undefined data in the popup map of Javascript

I am working with JSON data that is being displayed in a pop-up on a map. In cases where there is missing data (Visibility), the word undefined appears in the pop-up. Is there a way to remove the undefined text so that it does not show up in the pop-up? ...

Why is it that when drawing rectangles with HTML 5 canvas using pixel size, a black rectangle appears instead of blue?

My intention was to create a large blue rectangle measuring 320 X 240 pixels on the Canvas in Firefox, but I'm only getting a black rectangle instead. This issue is perplexing as I am simply experimenting with pixel drawing and for some reason, it&apo ...

Use the find() method in Vue.js to locate and correct this value

console.log(this.tiles.find(this.findStart)) When using the following code snippet: findStart: function (value) { var x = 5, y = 10; return value.x === x && value.y === y }, The expected results are returned. However, when su ...

Tips for Sharing Multiple Nested Arrays in AngularJS

I am working with an array in AngularJS, and here is an example: $scope.order.qty='20'; $scope.order.adress='Bekasi'; $scope.order.city='Bekasi'; To post this array, I use the following code: $http({ method : &ap ...

Uncover and control nested objects in JSON data

Having a dynamic foo object with the possibility of nested parent objects raises the question of how to effectively: 1) Determine the last object that has a parent? 2) Create an array containing all nested parent objects along with the initial obj (foo.o ...

how to make a scroll event bubble in rxjs

When using vanilla JavaScript, I can easily catch any scroll event on any element by including true as the last argument: document.addEventListener('scroll', function(e) { console.log(e); }, true); However, with rxjs it's not as straight ...

An issue has been encountered at the header component of an Angular web application, identified as error code

I recently created a small Angular web application and decided to create a Header component using the command line ng g c Header. https://i.sstatic.net/ZgCi0.pngI then proceeded to write a brief paragraph in the header.component.html file. <p>header ...