Home > Enterprise >  How binding another custom component dropdown value?
How binding another custom component dropdown value?

Time:11-11

I created a custom component for autocomplete dropdown with the html tag datalist, now how can I save the object in the component where I called its selector? I tried with [(ngModel)] but by object is undefined. How can I solve? Thanks in advance.

I saved the value in the custom component, but now I have to bring it to the component where I recalled it.

Call the dropdown component via the selector

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

My Custom Component .HTML

 <input type="text"  list="list" onfocus="this.value=''" [(ngModel)]="selectedTitle" (change)="saveElement($event)" (click)="slideOpen = !slideOpen">
<i  [class.clicked]="slideOpen"></i>
<datalist id="list">
<option *ngFor="let element of list" [value]="element.objectTitle">{{element.objectTitle}}</option>
</datalist>

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;

    selectedTitle?: String;

    slideOpen: any = false;

    public saveElement(e): void {
        let name = e.target.value;

        let element = this.list.filter(x => x.objectTitle === name)[0];
        this.selectedElement = element;
        this.selectedTitle = element.objectTitle;
        if (this.selectedElement == undefined) {
            e.target.value = "";
        }
    }
}

CodePudding user response:

You can implement an @Output EventEmitter and emit the new value to the parent like

@Output()
selected = new EventEmitter<YourElementType>();
...
this.selected.emit(listElement)

After that you can store the list in the parent component by using

<app-autocomplete-dropdown [list]="profiloList" (selected)="this.selectedItem = $event"></app-autocomplete-dropdown>

Note: You should avoid using an any type. Define an interface for your type and use it accordingly. This will help you in the long term.

  • Related