这个问题可能与其他问题类似,但我仍然找不到使我的代码工作的答案。我在我的应用程序中使用路由。我有两个组件:MenuComponent和PrincipalComponent。
在MenuComponent中,我有一个菜单(它被注入到app.component.html文件中,它显示了动物的列表,PrincipalComponent是我的默认路径,也是我想要在MenuComponent中显示所选动物(单击)的位置。我不知道如何将所选动物的响应发送到PrincipalComponent,并显示所选动物。

这是我的摘要代码,链接中有我的完整代码:
https://stackblitz.com/edit/angular-to5osq?file=app/menu.component.ts
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个页面并拥有一个向其发送信息的组件时应用此逻辑。
发布于 2019-03-21 14:41:11
您需要在router-outlet和<menu>中加载的组件之间共享数据。<router-outlet>发出一个事件(activate),它为您提供加载到outlet中的组件的实例。您可以将此实例保存在应用程序组件中。然后,使用AppComponent和MenuComponent的事件和父子关系,可以将所选对象的值设置为PrincipalComponent。
请参阅工作示例here
添加相关代码以供参考。
App.component.html
<router-outlet (activate)='onActivate($event)'></router-outlet>
<menu (setAnimal)='setAnimal($event)' ></menu>App.component.ts
private activatedComponent;
onActivate(component){
this.activatedComponent = component;
}
setAnimal(item){
console.log(item)
this.activatedComponent.animal = item.animal;
}MenuComponent
@Output() setAnimal: EventEmitter<any>;
constructor(){
this.setAnimal = new EventEmitter();
}
selectAnimal(item){
console.log(item);
this.setAnimal.emit(item);
}https://stackoverflow.com/questions/55274736
复制相似问题