简体   繁体   English

带有父/子组件的Angular 2/4管理表单CRUD

[英]Angular 2/4 managing form CRUD with parent/child components

  • I have a parent and a child component in which the parent is a list of repeating children using *ngFor. 我有一个父级和一个子级组件,其中父级是使用* ngFor的重复子级的列表。

  • each child takes in an object through the @Input feature of angular and the child template is a form which is bound using angular 2 way binding letting you edit the objects properties. 每个孩子都通过angular的@Input功能接收一个对象,而孩子模板是一种使用angular 2方式绑定来让您编辑对象属性的表单。

  • The parent is not necessarily a generic container/list for the child components and is not re-used for other lists. 父级不一定是子级组件的通用容器/列表,也不会再用于其他列表。

  • The parent uses an injected service to retrieve the list of data being used. 父级使用注入的服务来检索正在使用的数据列表。

my question is, who should call the update function when the form is being saved? 我的问题是, 保存表单时谁应该调用update函数? should the child have the service injected and it call the update function on the service? 孩子应该注入服务,并在服务上调用更新功能吗? should it be passed to the parent to be updated? 是否应该将其传递给父级进行更新? Should the child have read it to begin with? 孩子应该从头开始阅读吗?

I understand this could provoke opinionated answers so I am looking for an answer that would agree with what the Angular team intended for best practices and also match this criteria: 我知道这可能会引起别人的观点,所以我正在寻找一个与Angular团队旨在最佳实践相吻合并且也符合以下条件的答案:

  • even distribution between readability, performance and design. 可读性,性能和设计之间的均匀分配。
  • well rounded and related to commonly used software design patterns. 全面且与常用软件设计模式相关。

If any extra information is necessary please let me know, thanks!! 如果需要任何其他信息,请让我知道,谢谢!

I'd say, if parent component retrieves children using some service (most likely), then probably the same service handles save operation as well, and thus it is parent component who should be responsible for invoking save operation. 我要说的是,如果父组件使用某种服务(最有可能)检索子代,则可能相同的服务也处理保存操作,因此应该由父组件负责调用保存操作。 In this case child should only generate event to inform the parent of user's intention to save this particular item. 在这种情况下,孩子应该只生成事件以通知父母用户打算保存此特定项目的意图。 This way their responsibilities are better separated, since only one (parent) component is responsible for data operations on the service (one concern), while children are only responsible for showing and editing items (another concern). 这样,由于只有一个(父)组件负责服务上的数据操作(一个关注点),而孩子仅负责显示和编辑项目(另一个关注点),因此可以更好地分离他们的职责。

Maybe it just depends on where your update-button is placed. 也许这仅取决于更新按钮的放置位置。 If it's in the child component then call the service from child, otherwise call it from parent. 如果在子组件中,则从子组件调用服务,否则从父组件调用服务。

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

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