How to call sibling component method in angular 4?

谁说胖子不能爱 提交于 2019-12-10 11:41:29

问题


I have a header component which is having autocomplete search, when the user search something and select one item from the suggestions dropdown, the body will change accordingly. In body 3 sections are there which is showing based on three different conditions. Here header and body are 2 different components, Hence how to trigger the function in body which is having some logic along with false and true variables. when the user select something from the autocomplete search dropdown.
I am trying in a communication through service approach.
Header code

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


Body code

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

header component ts

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

planning service ts

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

and trying to catch the event from body component like this. But it is not triggering in body component. what is the issue
body component 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)
});

}

I am unable to catch the event from service in body component. Can anyone please help me

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


回答1:


To call a child component method from a parent component you can use ViewChild.

In your Parent class you would import the child component

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

and then use something similar:

@ViewChild(ChildComponent) childComponent: ChildComponent;

Then you will have access to your children component methods and properties:

childComponent.myMethod()

or

this.parentComponentValue = childComponent.property


来源:https://stackoverflow.com/questions/50408989/how-to-call-sibling-component-method-in-angular-4

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!