【问题标题】:accessing other components which are not children in Angular访问不是 Angular 中的子组件的其他组件
【发布时间】:2018-07-05 05:29:33
【问题描述】:

如何访问位于同一视图中但不是子视图的其他组件?我的父组件有一些组件。

parent.component.html

<html>
  <address-component></address-child>
  <name-component></name-component>
</html>

那么如何从address-component 访问name-component?除了处于同一个观点之外,他们没有自己的关系。

【问题讨论】:

  • 这取决于您要完成的工作。组件间通信本身并不是目的。
  • 我想获取视图中的名称组件,并从地址组件中调用名称组件中的方法。
  • 您可以将负责创建名称的方法抽象到服务中,并将该服务注入到两个组件中。
  • 我知道。我正在寻找不这样做的方法,因为我的详细用例不适合它。我正在寻找组件中的方法。比如访问表单并获取名称 -component从里面或类似的东西。
  • 您可以将name 组件作为输入参数传递给address 组件,如this stackblitz 所示(参见app.component.html 中的模板)。

标签: angular


【解决方案1】:

如果你不想使用服务,可以试试这个 child1-parent-child2 通信:

<address-component (updateNameComponent)="nameComponent.yourMethodName()"></address-child>
<name-component #nameComponent ></name-component>

在你的地址组件中,你会有这个:

@Output() updateNameComponent = new EventEmitter();

你可以使用这个从地址组件触发 nameComponent.yourMethodName:

updateNameComponent.emit();

【讨论】:

    猜你喜欢
    • 2017-10-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-11-07
    • 1970-01-01
    • 2013-01-02
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多