Angular 2 最佳实践:绑定对象与绑定其属性



子组件最好输入对象属性并更改发射器,还是像这样双向绑定到对象:

例 1

<parent-component>
  <child-component [exampleInput]="object.val" 
                   (valueChanged)="updateObjectValue($event)">
  </child-component>
</parent-component>

与示例 2

<parent-component>
  <child-component [(obj)]="object"></child-component>
</parent-component>

其中示例 2 的子组件将处理 updateObjectValue 逻辑。

在我们现在的代码中,像这样的组件目前有 4 个输入和 2 个输出,如果通过将它直接绑定到对象来减少到 1 个属性就可以了,那就太棒了

我会选择事件发射器选项,因为这是推荐的方式。请参考这个https://angular.io/guide/component-interaction#parent-listens-for-child-event

<parent-component>
     <child-component [exampleInput]="object.val"
        (valueChanged)="updateObjectValue($event)">
     </child-component>
</parent-component>

最新更新