简体   繁体   English

将组件作为输入传递

[英]passing a component as an Input

Im trying to build a generic timeline component that accepts an array of items.我正在尝试构建一个接受一系列项目的通用时间线组件。 a timeline's item is an object that contain icon, content and an extendable content.时间线的项目是包含图标、内容和可扩展内容的 object。

When a timeline's item is clicked the extendable content is extended with a style and a logic of it's on, in other words, when item is clicked a new component is open in the timeline's item position.当单击时间线的项目时,可扩展内容会使用样式和逻辑进行扩展,也就是说,当单击项目时,时间线的项目 position 中会打开一个新组件。

I dont have any good ideas so far, except from passing the extendable content as a component.到目前为止,我没有任何好主意,除了将可扩展内容作为组件传递。

Is there a better solution?有更好的解决方案吗?

In my experience, you have three options to complete your objective.根据我的经验,你有三种选择来完成你的目标。

Option 1): Pass data as @Input()选项 1):将数据作为 @Input() 传递

You can pass the object data as @Input() of the Child Component: https://angular.io/guide/component-interaction#pass-data-from-parent-to-child-with-input-binding您可以将 object 数据作为子组件的 @Input() 传递: https://angular.io/guide/component-interaction#pass-data-from-parent-to-child-with-input-binding

Option 2): Share Data through a Service with Subject/BehaviorSubject选项 2):通过带有 Subject/BehaviorSubject 的服务共享数据

You can create a Services that contains a property with type Subject/BehaviorSubject, then the Parent Component set the data to share in the property of the service and finally the Child Component access to that data in the property of the service:您可以创建一个包含 Subject/BehaviorSubject 类型的属性的服务,然后父组件将数据设置为在服务的属性中共享,最后子组件在服务的属性中访问该数据:

https://angular.io/guide/component-interaction#parent-and-children-communicate-via-a-service https://angular.io/guide/component-interaction#parent-and-children-communicate-via-a-service

Option 3): Set the data in the Child Component with @ViewChild(): https://angular.io/guide/component-interaction#parent-calls-an-viewchild选项3):使用@ViewChild()设置子组件中的数据: https://angular.io/guide/component-interaction#parent-calls-an-viewchild

For your case, I recommend you to share data with the @Input() property in the Child Component (Option 1).对于您的情况,我建议您与子组件中的 @Input() 属性共享数据(选项 1)。

Another case, for large application and multiples modules you can use a State Management Library like NgRx or NGXS .另一种情况,对于大型应用程序和多个模块,您可以使用 State 管理库,如NgRxNGXS I recommend you NGXS.我推荐你NGXS。

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

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