【问题标题】:Angular - How to send Data from Child Component to Parent with Routing?Angular - 如何通过路由将数据从子组件发送到父组件?
【发布时间】:2019-12-20 02:26:27
【问题描述】:

我想设置一个 SampleData 并将其发送到 Angular 中的父组件。 当子组件完全在父组件内部时,它可以正常工作。

但是,我想通过路由在父组件中设置不同的子组件。

所以我把 放在 parent.component.html 中, 并且子组件是这样调用的,不再起作用了……

{ path: "sample1", component: Sample1Component }

谁能看到我的代码并给我一个解决方案...?

中心组件将是父组件, Sample1 组件将是子组件。

您可以从Here下载代码以查看更多详细信息

app.router.module.ts

const AppRoutes: Routes = [
  { path: "", redirectTo: "/", pathMatch: "full" }, 
  { path: "sample1", component: Sample1Component },
  { path: "**", redirectTo: "/", pathMatch: "full" } 
];

center.component.html

<div (sampleEvent)="SampleData = $event">
  Center Area Title from Sample 1 : {{ SampleData }}
</div>

<!--if sample 1 Component is called by this Router, 'Center Area Title value does not change -->
<router-outlet></router-outlet>

<!-- if sample 1 Component is called by below, 'Center Area Title value changes-->
<!-- <app-sample1 (sampleEvent)="SampleData = $event"></app-sample1> -->

sample1.component.html

<input type="text" placeholder="Center Area Title" #sampleTitle (keyup)="onChange(sampleTitle.value)"  />

sample1.component.ts

export class Sample1Component implements OnInit {
  @Output("sampleEvent") sampleEvent = new EventEmitter();

  onChange(value) {
    console.log(value);
    this.sampleEvent.emit(value);
  }

  constructor() {}
  ngOnInit() {}
}

请有人帮帮我....

【问题讨论】:

标签: angular


【解决方案1】:

路由组件与包含RouterOutlet (&lt;router-outlet&gt;) 的组件没有内在关系。 可能找到一种通过RouterOutlet 从路由组件发出数据的方法,但这不是解决此问题的规范方法。更传统的解决方案是使用外部单例(服务),其中包含用于在不具有直接继承关系的组件之间传输数据的可观察对象。

  1. 为事件创建一个带有 Subject 字段的 @Injectable() 服务类
  2. 将此服务添加到模块提供程序
  3. 将此服务注入到路由组件(Sample1Component)和容器组件(CenterComponent)中
  4. 监听容器组件中可观察字段的变化 (CenterComponent)
  5. 将更改发送到路由组件中的可观察主题 (Sample1Component)

【讨论】:

  • 感谢您的回答。现在,我使用 Service 根据您的评论实现了我想要的。 :))))
猜你喜欢
  • 2021-02-15
  • 2018-07-07
  • 2016-09-05
  • 2018-08-12
  • 2016-03-18
  • 2017-09-13
  • 1970-01-01
  • 2021-03-22
  • 2018-09-04
相关资源
最近更新 更多