簡體   English   中英

如何在 Angular 中調用兄弟組件方法?

[英]How to call sibling component method in Angular?

我有一個標題組件,它具有自動完成搜索功能,當用戶搜索某些內容並從建議下拉列表中選擇一項時,正文會相應地更改。 在正文中,有 3 個部分,它們基於三種不同的條件顯示。 這里 header 和 body 是 2 個不同的組件,因此如何觸發 body 中的函數,它具有一些邏輯以及 false 和 true 變量。 當用戶從自動完成搜索下拉列表中選擇某些內容時。
我正在嘗試通過服務方法進行通信。
標題代碼

<div class="docs-example-viewer-body custom-search" *ngIf="showSearch">
  <select class="search-dropdown">
    <option value="1">All</option>
    <option value="2">Brand</option>
    <option value="3">Molecule</option>
  </select>
  <app-auto-complete [mySearchData]="mySearchData" (onchange)="onchange($event)" (onsearchKey)="getOnsearchkey($event)"></app-auto-complete>
  <i class="material-icons">search </i>
</div>


體碼

<div *ngIf="aaa"> 123</div>
<div *ngIf="bbb"> 333</div>

頭組件 ts

onChange(value) {
  this.planningService.changeOccured(value);
}

規划服務ts

@Output() change: EventEmitter<any> = new EventEmitter();
changeOccured(value) {
  this.change.emit(value);
}

並試圖從這樣的 body 組件中捕獲事件。 但它不會在身體組件中觸發。 這是什么問題
身體成分 ts

onChange(value){
this.isSearchScreen = false;
this.isPlanListScreen = true;
this.isCreateScreen = false;
console.log('value',value)
this.myPlan.moleculeId = value.id;
this.selectedCombination = new SelectedCombination(value.brand,value.name);
this.planningService.getProductMapData(value.name).subscribe((data)=>{
  this.strengthANdPacks = data;
},(error)=>{
  console.log(error);
});
this.planningService.getAllPlans(value.id,false).subscribe((data)=>{
  this.allPlans = data;

},(error)=>{
  console.log(error);
});
}

ngOnInit(){
this.planningService.change.subscribe(value => {
  console.log('change occured')
 this.onChange(value)
});

}

我無法從 body 組件中的服務中捕獲事件。 誰能幫幫我嗎

參考: https : //medium.com/dailyjs/3-ways-to-communicate-between-angular-components-a1e3f3304ecb

要從父組件調用子組件方法,您可以使用 ViewChild。

在您的父類中,您將導入子組件

import { ChildComponent } from './child-component.ts';

然后使用類似的東西:

@ViewChild(ChildComponent) childComponent: ChildComponent;

然后您將可以訪問您的子組件方法和屬性:

this.childComponent.myMethod()

或者

this.parentComponentValue = childComponent.property

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM