【问题标题】:Return values using EventEmitter angular2使用 EventEmitter angular2 返回值
【发布时间】:2018-02-20 15:52:55
【问题描述】:

我有一个在父组件中发出事件的EventEmitter,我希望它从父组件执行一系列指令,结果返回给调用者, this.filteredList 我希望它包含父组件返回的列表,但是当它返回时,filteredList 是未定义的

这是 de chid 组件“autocomplete.component.ts:” //当在this.changeFilter.emit中返回时,this.filteredList是未定义的:

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); 
      }
    }

模板:

    <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>

这是父组件“busquedacompiadoras.component.ts”:

//函数“onChangeFilterClientes”返回一个带有数据的列表,但是当它返回到子组件的eventEmitter时this.filteredList是未定义的 //有什么想法吗?

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; 
}

【问题讨论】:

  • 因为EventEmitter 基于Observable 并且操作是异步的(稍后发生,当您当前的同步代码块完成时)。您需要检查 examplengOnChanges 以获得有关何时发生值更新的通知。
  • filteredList 定义为@Input(),并将其设置在父级中。无需从onChangeFilterClientes 返回任何值。将clientesFilter 传递给孩子[filteredList]="clientesFilter" (HTML)
  • 对不起,我不明白,你可以举个例子解释一下吗?

标签: angular eventemitter emit


【解决方案1】:

尝试以下方法:

导出类 AutocompleteComponent 实现 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}); 
}

并在 BusquedaCopiadorasComponent 模板中传递过滤列表,如下所示:

 [filteredList]="clientesFilter"

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-07-14
    • 2016-11-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-09-26
    • 1970-01-01
    相关资源
    最近更新 更多