Search code examples
angulareventemitteremit

Return values using EventEmitter angular2


I have an EventEmitter that issues an event in the parent component, I want it from the parent component to perform a series of instructions and the result returns it to the caller, this.filteredList I want it to contain the list returned by the parent component but when it returns, filteredList is undefined

This is de chid component "autocomplete.component.ts:" //When returns in this.changeFilter.emit, this.filteredList is undefined:

export class AutocompleteComponent implements OnInit {
    ...

    public filteredList = [];

    @Output() changeFilter = new EventEmitter<any>();


    filter(){
     //This is where I want the filteredList to contain the list returned by the other component:
     this.filteredList =this.changeFilter.emit({query:this.query}); 
     if (filteredList){
        console.log(filteredList); 
      }
    }

the template:

    <div class="container">
    <div class="input-field col s12">
      <input id="clienteAut" type="text" class="form-control bs-autocomplete" style="width:300px;" [(ngModel)]="query" (keyup)="filter()" on-click="filterAll()">
      <label for="clienteAut"></label>
    </div>
    <div class="divLista" *ngIf="filteredList.length > 0" style="">
      <div class="divFila" *ngFor="let item of filteredList">
        <ul >
          <li>
            <a (click)="select(item)">{{item.CodigoCliente}} - {{item.Nombre}}</a>
          </li>
        </ul>
      </div>
    </div>
    </div>

This is the parent component "busquedacompiadoras.component.ts":

//The function "onChangeFilterClientes" return a list with data, but when it returns to the eventEmitter of the child component this.filteredList is undefined //Any ideas?

export class BusquedaCopiadorasComponent {  

clientes: Array<any> //= [];

ngOnInit() {
    this._comunService.getMarcas()
        .subscribe((clientesData) => {
            this.clientes = clientesData as clienteModel[];
            //this.rellenarMarcas(marcasData);
        });
}    

onChangeFilterClientes(obj:any):any[]{        
     this.clientesFilter = this.clientes.filter(c => c.Nombre.toString().toLowerCase().indexOf(obj.query)>-1);       
     return this.clientesFilter; 
}

Solution

  • Try the following:

    export class AutocompleteComponent implements OnInit { ...

    @Input() public filteredList = [];
    
    @Output() changeFilter = new EventEmitter<any>();
    
    
    filter(){
     //This is where I want the filteredList to contain the list returned by the other component:
     this.changeFilter.emit({query:this.query}); 
    }
    

    And in the BusquedaCopiadorasComponent template pass the filteredList as below:

     [filteredList]="clientesFilter"