将数据从childA组件一直传递到其父组件,然后再传递到childB组件 [英] Passing data all the way from childA component to its parent component and then to childB component

查看:110
本文介绍了将数据从childA组件一直传递到其父组件,然后再传递到childB组件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个父级组件,并且有两个子级,1.app-search-list和2.app-vertical-menu

I have a parent component and it has two child , 1.app-search-list and 2.app-vertical-menu

我正在将数据从app-search-list(childA)组件传递到其父组件,然后从父传递到app-vertical-menu组件(childB),如图所示

I am passing data from app-search-list(childA) component to its parent component and then from parent to the app-vertical-menu component(childB) as shown in the image

您可以在stackblitz上找到代码的链接

You can find the link to the code on stackblitz here

以这种方式传递数据可以正常工作,但是如果我们去其他路线然后返回并从选择列表组件中单击列表,数据未按预期传递.我拍了一段视频来解释这个问题.这是链接到它

Passing data in this way is working fine but if we go to any other routes and come back and click the list from the select list component , The data is not passing as expected. I have made a video to explain the problem. Here is the link to it

推荐答案

问题是,当已经选择了一个组时,它将仅在以下情况下更新为子组件( vertical-menu.component ):父级( app.component )中对该值的引用已更改.因此,如果单击已选择的组,则不会发生任何事情,因为它将引用同一对象.这是由于角度变化检测.

The problem is that when a group is already selected it will only update to the child component (vertical-menu.component) when the reference to the value has changed in the parent (app.component). So if you click a Group that is already selected nothing will occur because it will reference the same object. This is due to change detection in angular.

一种解决方案是简单地创建从 search-list.component 发出的对象的新实例.

One solution is to simply create a new instance of the object being emitted from search-list.component.

public onClickList(list:any) {
  const selected = Object.assign({}, list);
  this.selectedList.emit(selected);
}

下面的链接是我认为您要完成的事情的分叉式堆叠.

Linked below is a forked stackblitz of what I think you're trying to accomplish.

https://stackblitz.com/edit/github-n9pmlg-6fds9q

https://medium.com/@bencabanes/angular-change-detection-strategy-an-introduction-819aaa7204e7

这篇关于将数据从childA组件一直传递到其父组件,然后再传递到childB组件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆