在 Angular 中的 parent 模板中调用 child 组件的方法是一种好习惯吗?
Is it a good practice to call a method of a child component inside the parent's template in Angular?
我有一个 parent 组件,它基本上是由两个 child 组件组成的表单,每个组件都由一堆 inputs
组成。这是 parent 组件模板:
<!-- Bunch of user selected filters -->
<app-filters #filters>
</app-filters>
<!-- Bunch of user selected grouping options -->
<app-grouping-options #groupingOptions>
</app-grouping-options>
<!-- Emit an event with the composed query so
other component can recover and show the data
to the user -->
<button (click)="emitQuery(filters.getFilteringCriteria(), groupingOptions.getGroupingCriteria())">Search</button>
我感兴趣的部分是 filters.getFilteringCriteria()
和 groupingOptions.getGroupingOptionsCriteria()
方法调用。我不确定这是否是一个好的做法,特别是因为它似乎破坏了预期的数据流:from parents to children through 属性绑定,并通过事件从children到parent。但是我真的不知道在这种情况下如何进行,因为搜索的功能确实是一种方法,而不是属性。
除此之外,引用 child 组件的最佳方法是什么?通过模板变量或使用 @ViewChild
?
感谢您的帮助。
这不是最佳做法,因为这意味着您的组件紧密耦合(这意味着您的第一个组件依赖于其他 2 个)。
如果您想使用最佳实践,请依靠 @Input
的筛选器(更改子项中的筛选器将更改父项中的筛选器),以及 @Output
的分组选项(使用事件发射器将事件传播到父级)。
现在请不要误会我的意思:做你所做的完全没问题。这只是意味着,如果你想这样做,就必须付出额外的努力才能使你的组件通用。
如果没有,那就保留它,即使 SOF 上的人告诉你不要这样做。您没有被迫重用组件!
我有一个 parent 组件,它基本上是由两个 child 组件组成的表单,每个组件都由一堆 inputs
组成。这是 parent 组件模板:
<!-- Bunch of user selected filters -->
<app-filters #filters>
</app-filters>
<!-- Bunch of user selected grouping options -->
<app-grouping-options #groupingOptions>
</app-grouping-options>
<!-- Emit an event with the composed query so
other component can recover and show the data
to the user -->
<button (click)="emitQuery(filters.getFilteringCriteria(), groupingOptions.getGroupingCriteria())">Search</button>
我感兴趣的部分是 filters.getFilteringCriteria()
和 groupingOptions.getGroupingOptionsCriteria()
方法调用。我不确定这是否是一个好的做法,特别是因为它似乎破坏了预期的数据流:from parents to children through 属性绑定,并通过事件从children到parent。但是我真的不知道在这种情况下如何进行,因为搜索的功能确实是一种方法,而不是属性。
除此之外,引用 child 组件的最佳方法是什么?通过模板变量或使用 @ViewChild
?
感谢您的帮助。
这不是最佳做法,因为这意味着您的组件紧密耦合(这意味着您的第一个组件依赖于其他 2 个)。
如果您想使用最佳实践,请依靠 @Input
的筛选器(更改子项中的筛选器将更改父项中的筛选器),以及 @Output
的分组选项(使用事件发射器将事件传播到父级)。
现在请不要误会我的意思:做你所做的完全没问题。这只是意味着,如果你想这样做,就必须付出额外的努力才能使你的组件通用。
如果没有,那就保留它,即使 SOF 上的人告诉你不要这样做。您没有被迫重用组件!