简体   繁体   English

角度2/4亲子沟通

[英]Angular 2/4 parent child communication

i am programming app which has parent-child relationship, and i am looking for best-practice for handling data/event flow. 我正在编程的应用程序具有亲子关系,我正在寻找处理数据/事件流的最佳实践。 parent has list of items which are sent to child component. 父级具有发送到子级组件的项目列表。

Child component has data entries for updating current values. 子组件具有用于更新当前值的数据条目。 At this moment, updating values are being handled from children. 目前,正在从子级处理更新值。 I've made following: when i get success from server,i just make sure that child values are ok. 我做了以下几点:当我从服务器获得成功时,我只是确保子级值正确。 I've made possible that this data is propagated to parent (eventEmitter) but at this moment i am not doing anything with this? 我已经有可能将此数据传播到父对象(eventEmitter),但是现在我对此不做任何事情? Should I be using two-way data binding here or not? 是否应在此处使用双向数据绑定? Or should i use onActivityUpdated to propagate that item to parent? 还是我应该使用onActivityUpdated将该项目传播给父级? Should child be handling call to service and updating that value? 孩子应该处理呼叫服务并更新该值吗?

Children list is shown as a list (all data on same page), so it's possible to edit one child, then another, ... and then there should be save all option from parent. 子级列表显示为列表(所有数据都在同一页面上),因此可以编辑一个子级,然后编辑另一个子级,...,然后应保存父级的所有选项。 What is the most optimal way to handle this? 处理此问题的最佳方法是什么? Should parent initiate call to service and then change all values? 父母应该发起服务呼叫,然后更改所有值吗?

here's code so far, i've ommited most of the unneccessary stuff... 到目前为止,这里是代码,我省略了大多数不必要的内容...

parent has a list of items, which is sent to children like this: 父母有一个物品清单,像这样发送给孩子:

ts: ts:

export class ParentComponent implements OnInit {
//Filtered items
@Input()
public items: Client[];

html: 的HTML:

<case-activity-time-edit-item *ngFor="let item of items; let i = index" [(element)]="items[i]" (activityUpdated)="onActivityUpdated($event)"></case-activity-time-edit-item></div>

here's child: 这是孩子:

export class ChildComponent implements OnInit {
@Input()
public element: Client;

@Output()
public activityUpdated: EventEmitter<Client> = new EventEmitter<Client>();

Everything you're doing looks good. 您所做的一切看起来都不错。 My only suggestion is to keep the parent and child value in sync using two way binding: 我唯一的建议是使用两种方式使父和子值保持同步:

_element: Client;
@Input() set element(val) {
  this._element = val;
}
get element() {
  return this._element;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM