skip to Main Content

I have the following code:

<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 want to get the object category but I can only get a string ‘object Object’ which I can’t properly transform back to the object. Is there a way to use native select and get the object element for the function in ‘(change)’?

2

Answers


  1. You have to serialize your category object, only string value are usable in a select. So use:

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

    And then wherever you want to grab this category (so, in your case the method your Output is emitting to), deserialize the category object by using:

    methodPointedByTheOutput(serializedCategory:string){    
    let category = JSON.parse(serializedCategory) as Category;
    
    //Do something
    }
    
    Login or Signup to reply.
  2. Try adding a method in the component which will then emit the object value, instead from the template:

    Try this:

    call new getCategory helper method, set category.id as an option value, to easily find the object later:

    <select #categorySelect (change)="getCategory(categorySelect.value)" style="...">
    
    
    [ngValue]="category.id" 
    

    Add new method which will find the object and emit it from there:

      getCategory(id:string) {
        
        const categorySelect = this.categories.find(el=>el.id === id);
    
        this.goToCategory.emit(categorySelect);
      }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search