【问题标题】:How can I access from a child component to another child component in Angular 4 [duplicate]如何在Angular 4中从子组件访问另一个子组件[重复]
【发布时间】:2017-12-23 12:56:09
【问题描述】:

我有一个父组件,里面有 2 个不同的子组件。 当我点击第一个子组件中的链接时,我需要从第一个子组件调用第二个子组件的函数。

所以这里有一个基本图可以更好地解释:

【问题讨论】:

标签: angular angular-components


【解决方案1】:

您可以通过ViewChildOutput 进行归档

例如:

@Component({
  template: '
     <child-one (clicked)="handleClick()"></child-one>
     <child-two></child-two>
  '
})
export class ParentComponent {
   @ViewChild(ChildOneComponent)
   childOne: ChildOneComponent;

   handleClick(){
    this.childOne.doSomething();
   }
}

在这种情况下:

  • clickedChildOneComponentOuput 属性
  • doSomething 是一个公共方法

另一种只使用Output 和模板变量的方法

@Component({
      template: '
         <child-one (clicked)="childTwo.doSomething()"></child-one>
         <child-two #childTwo></child-two>
      '
    })
    export class ParentComponent {

    }

【讨论】:

  • 谢谢你,实际上我现在正在尝试这样做。等我写完再写。
  • 谢谢,我终于做到了,这个也帮了我,stackoverflow.com/questions/41954484/…
  • 另一种解决方案是在这两个组件之间使用服务,上面的链接也提到了这一点
  • 如果您想在组件之间交换数据,特别是在没有父子关系的情况下,服务将是更好的方法。仅仅调用一个方法,当一个事件被捕获时,这种方法是可以的
猜你喜欢
  • 2018-02-20
  • 2020-07-10
  • 1970-01-01
  • 2016-09-28
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-06-12
  • 2020-06-18
相关资源
最近更新 更多