Home > Enterprise >  Angular shows [Object object] instead of value
Angular shows [Object object] instead of value

Time:11-11

Instead of my datalist option value i see only "[Object object]", i tried to pipe json like this: {{element.objectTitle | json}} I encountered this problem when I created the custom component, before I didn't have it.

My Custom Component HTML:

<div style="position: relative;" >
    <input id="profileInput" type="text"  list="profiles" onfocus="this.value=''"
        [(ngModel)]="selectedElement" (change)="saveCode($event)" (click)="changeSlide()">
    <i  [class.clicked]="slideOpen"></i>

    <datalist id="profiles">
        <option *ngFor="let element of list" [value]="element.objectTitle">
            {{element.objectTitle}}</option>
    </datalist>
</div>

My Custom Component Ts:

import { Component, OnInit, Input } from '@angular/core';

@Component({
    selector: 'app-autocomplete-dropdown',
    templateUrl: './autocomplete-dropdown.component.html',
    styleUrls: ['./autocomplete-dropdown.component.scss']
})
export class AutocompleteDropdownComponent implements OnInit {

    @Input()
    list: any;

    selectedElement: any;

    slideOpen: any = false;

    public saveCode(e): void {
        let name = e.target.value;
        let element = this.list.filter(x => x.objectTitle === name)[0];
        this.selectedElement = element;
    }

    changeSlide(): void {
        this.slideOpen = !this.slideOpen;
    }

}

Calling My Component like this:

<app-autocomplete-dropdown [list]="profiloList"></app-autocomplete-dropdown>

CodePudding user response:

You get "[Object object]" string value because of current control usage. The ngModel control is used in input element, and this means it can store only a string value. Exactly what you get.

To store selected object value just create another property and check it when needs:

selectedElement: any;

...
selectedValue: any;

public saveCode(e): void {
    const name = this.selectedElement;
    const element = this.list.find(x => x.objectTitle === name);
    this.selectedValue = element;
}
  • Related