【问题标题】:How to call sibling component method in Angular?如何在Angular中调用兄弟组件方法?
【发布时间】:2018-10-28 18:10:52
【问题描述】:

我有一个具有自动完成搜索功能的标题组件,当用户搜索某些内容并从建议下拉列表中选择一项时,正文将相应更改。在正文中,有 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 组件中捕获事件。但它不会在身体组件中触发。有什么问题
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)
});

}

我无法从正文组件中的服务中捕获事件。谁能帮帮我

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

【问题讨论】:

标签: angular typescript components angular-services


【解决方案1】:

要从父组件调用子组件方法,您可以使用 ViewChild。

在您的 Parent 类中,您将导入子组件

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

然后使用类似的东西:

@ViewChild(ChildComponent) childComponent: ChildComponent;

然后您将可以访问您的子组件方法和属性:

this.childComponent.myMethod()

this.parentComponentValue = childComponent.property

【讨论】:

  • Giving error AppHeaderComponent.html:63 ERROR TypeError: Cannot read property 'myMethod' of undefined
  • 这是您问题的一部分 - 如何在另一个组件中调用方法。要获取更新后的值,您可以在父组件中调用子组件中更新的属性并将其值分配给父组件属性。
  • @ThilakRaj - 看到你更新了问题 - 你能发布更多代码吗?亲子班?
  • 只是为了澄清,在组件中使用 this.childComponent.myMethod() 向其兄弟组件触发函数。
猜你喜欢
  • 2017-10-21
  • 1970-01-01
  • 2018-06-27
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-06-23
相关资源
最近更新 更多