首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何从一个组件(<menu> </ menu>)执行函数,并将结果传输到另一个组件?

如何从一个组件(<menu> </ menu>)执行函数,并将结果传输到另一个组件?
EN

Stack Overflow用户
提问于 2019-03-21 14:17:14
回答 1查看 43关注 0票数 0

这个问题可能与其他问题类似,但我仍然找不到使我的代码工作的答案。我在我的应用程序中使用路由。我有两个组件:MenuComponentPrincipalComponent

MenuComponent中,我有一个菜单(它被注入到app.component.html文件中,它显示了动物的列表,PrincipalComponent是我的默认路径,也是我想要在MenuComponent中显示所选动物(单击)的位置。我不知道如何将所选动物的响应发送到PrincipalComponent,并显示所选动物。

这是我的摘要代码,链接中有我的完整代码:

https://stackblitz.com/edit/angular-to5osq?file=app/menu.component.ts

代码语言:javascript
复制
export class MenuComponent  {
aAnimals=
[
  {"animal":"cat"},
  {"animal":"dog"},
  {"animal":"horse"}
]
Select a animal: <br> <button *ngFor="let item of aAnimals" (click)="getAnimal(item);" style="display:block;">{{item.animal}}</button>
export class PrincipalComponent  {
  animal:any;
  constructor(){

  }

  getAnimal(item){
    console.log(item);
    this.animal=item.animal;
  }
  <h1>animal selected: {{animal}}</h1>

解决这个问题将解决许多疑问,我可以在创建n个页面并拥有一个向其发送信息的组件时应用此逻辑。

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2019-03-21 14:41:11

您需要在router-outlet<menu>中加载的组件之间共享数据。<router-outlet>发出一个事件(activate),它为您提供加载到outlet中的组件的实例。您可以将此实例保存在应用程序组件中。然后,使用AppComponentMenuComponent的事件和父子关系,可以将所选对象的值设置为PrincipalComponent

请参阅工作示例here

添加相关代码以供参考。

App.component.html

代码语言:javascript
复制
<router-outlet (activate)='onActivate($event)'></router-outlet>
<menu (setAnimal)='setAnimal($event)' ></menu>

App.component.ts

代码语言:javascript
复制
private activatedComponent;
onActivate(component){
this.activatedComponent = component;
}

setAnimal(item){
    console.log(item)
    this.activatedComponent.animal = item.animal;
}

MenuComponent

代码语言:javascript
复制
@Output() setAnimal: EventEmitter<any>;
constructor(){
  this.setAnimal = new EventEmitter();
}

selectAnimal(item){
  console.log(item);
  this.setAnimal.emit(item);
}
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/55274736

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档