我有一個EventEmitter在父組件中發出一個事件,我希望它從父組件執行一系列指令並將結果返回給調用者,this.filteredList我希望它以包含由父組件返回的列表,但是當它返回時,filteredList是undefined使用EventEmitter的返回值angular2
這是de chid組件「autocomplete.component.ts:」 //當在this.changeFilter.emit中返回時,this.filteredList是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);
}
}
模板:
<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。 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'並且動作是異步的c(稍後發生,當前您的同步代碼塊完成時)。您需要檢查例如'ngOnChanges'以獲知有關值更新何時發生的通知。 –
將'filteredList'定義爲'@Input()',並將其設置在父項中。不需要從'onChangeFilterClientes'返回任何值。將'clientesFilter'傳遞給子['filteredList] =「clientesFilter」'(HTML) – Arg0n
對不起,但我不明白,你可以舉一個你的解釋的例子嗎? – ararb78