2017-04-17 138 views
0

我在Angular应用程序中有一个主组件和许多子组件。我使用的是渲染子组件。像这样的东西。组件间事件绑定Angular 2

<body class="nav-md"> 
    <mainComponent></mainComponent> 
    <router-outlet></router-outlet> 
</body> 

我的主要组件有一个搜索框和一个按钮。当我点击mainComponent中的按钮时,我想调用我的子组件的函数。任何帮助,将不胜感激。

+0

请新增主要成分和子组件的HTMl \ TS的代码,这样任何一个可以提供帮助。 –

回答

1

在这种情况下,您可以使用ViewChild

例子:

import { Component, ViewChild } from '@angular/core'; 
import { ChildComponent } from '../child.component'; 

@Component({ 
    selector: 'mainComponent', 
    template: '<search (onSearch)="onSearch($event)"></search><child-component></child-component>', 
}) 
export class MainComopnent{ 
    // ViewChild takes a class type or a reference name string. 
    // Here we are using the type 
    @ViewChild(ChildComponent) child: ChildComponent; 

    onSearch(search: string) { 
     this.child.say(search); 
    } 
} 

@Component({ 
    selector: 'child-component' 
}) 
export class ChildComponent { 
    say(something: string) { 
     console.log(something); 
    } 
} 
+1

虽然这个链接可能回答这个问题,但最好在这里包含答案的基本部分,并提供供参考的链接。如果链接页面更改,则仅链接答案可能会失效。 - [来自评论](/ review/low-quality-posts/15865487) – Adam

+0

@Adam好点,我做到了。 – LLL