简体   繁体   English

将巨大的 object 从父组件传递给子组件

[英]Passing huge object from parent to child component

I am refactoring a code where I want to pass down several properties to a reusable child component -- but without using too many inputs (which is the current problem).我正在重构一个代码,我想将几个属性传递给一个可重用的子组件——但不使用太多输入(这是当前的问题)。

The problem is that, even with my current approach, the html code looks shabby because of passing down a huge object (below is just an example. The object can be bigger since there are many properties to be passed to child).问题是,即使使用我目前的方法,html 代码看起来很破旧,因为传递了一个巨大的 object(下面只是一个例子。object)可以更大,因为有很多属性可以传递给孩子。

My code looks something like below:我的代码如下所示:

<app-parent>
<ul>
  <li
    *ngFor="let prop of props"
    <app-child
    [childProps]="{'template':'parent1', 'iconName':prop.type | propIcon, 'showIcon':true}"
  >
    </app-child>
  </li>
</ul>
</app-parent>

Is there an alternative approach that follows best practices and at the same time makes the code more readable?是否有遵循最佳实践并同时使代码更具可读性的替代方法?

In component.ts create a new mapped array:在 component.ts 创建一个新的映射数组:

let mappedProps: ChildProp[] = props.map((prop) => ({
   ...prop, // Make sure all values from the old props array are here as well
   template: 'parent1',
   showIcon: true
}));

Afterwards in component.html:然后在component.html中:

<app-parent>
<ul>
  <li
    *ngFor="let prop of mappedProps"
    <app-child [childProp]="prop">
    </app-child>
  </li>
</ul>
</app-parent>

Notice I changed the child input value to childProp since you are only passing one object down there, not an array请注意,我将子输入值更改为childProp ,因为您只在下面传递了一个 object,而不是数组

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

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