如何在Angular 4中从子组件访问另一个子组件 [英] How can I access from a child component to another child component in Angular 4

查看:61
本文介绍了如何在Angular 4中从子组件访问另一个子组件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个父组件,内部有2个不同的子组件. 单击第一个子组件中的链接时,我需要从第一个子组件中调用第二个子组件的功能.

I have a parent component and inside there are 2 different child components. I need to call the second child component's function from the first child component when I click a link in the first child component.

因此,这是一个可以更好地解释的基本图表:

So here is a basic diagram to explain better:

推荐答案

您可以通过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是公共方法
  • clicked is an Ouput property of ChildOneComponent
  • doSomething is a public method

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

Another approach only ussing Output and a template variable

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

    }

这篇关于如何在Angular 4中从子组件访问另一个子组件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆