有没有办法使Child组件能够调用兄弟姐妹功能。

时间:2016-05-11 18:34:18

标签: angular

我有两个具有相同父级的组件。组件1中有一个搜索按钮,组件2中有一个刷新按钮。我希望这两个按钮做同样的事情并调用组件1中的一个函数。组件2有没有办法在组件1中调用该函数或能够点击搜索按钮。

2 个答案:

答案 0 :(得分:0)

我最终在Child2组件中创建了一个EventEmitter刷新。单击刷新按钮时,它会将事件发送到父组件。然后,父组件将使用模板变量调用子组件上的搜索。

//home component
     //child 1 with variable
    <search #Search><search>
//html code
     ///child 2 calling search on child 1. 
    <results (refreshEvent)="Search.onSearch()"></results>

答案 1 :(得分:-1)

你需要利用@ViewChild装饰器,你必须使用component1和component2之间的父子关系,以便从另一个中调用其中一个函数,从父元素引用子元素(component1)组件(component2)通过注射:

import { Component, ViewChild } from 'angular2/core';  

(...)

@Component({
  selector: 'my-app',
  template: `
    <h1>My First Angular 2 App</h1>
    <child></child>
    <button (click)="someOtherMethod()">Call Function from Comp1</button>
  `,
  directives:[Component1]
})
export class AppComponent { 
  @ViewChild(Component1) comp1:Component1;

  (...)

  someOtherMethod() {
    this.comp1.functToCallInComp1();
  }
}