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

查看:25
本文介绍了如何从子组件访问 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天全站免登陆