2016-08-01 61 views
2

想象一下这样的主机组件代码:呼叫嵌套组件功能angular2

@Component({ 
    directives: [nestedComponentDirective] 
}) 

export class ParentComponent { 
    save():void { 
      this.myService.myHTTPCall().subscribe((event) => { 
       // if callback successfull we need to let directive know 
      }) 
     } 

现在嵌套组件:

@Component({ 
    selector: 'someSelector', 
    template: ` 
    <div> 
    <button [stuff]="stuff"</button> 
    </div>` 
}) 


export class ContinuationCheckDirective { 
    @Input() waitingForHostedComp(value) { 
    console.log ("value", value) 
    } 

如何从主机的组件(父)调用waitingForHostedComp?

+0

请提供更多代码。 'save()'和'waitingForHostComp()'在哪里? –

+0

'save()'在ParentComponent中导入ChildComponent。 'waitingForHostComp()'在ChildComponent上。基本上我想要的是当ParentComponent(注入ChildComponent)从服务器获取答案时触发ChildComponent。 – nottinhill

回答

6

您可以这样做的方式是使用ViewChild,即我们将子组件注入父代作为ViewChild

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

@Component({ 
    selector: 'parent-component', 
    template: ` implements AfterViewInit 
    <child-component></child-component> 
    `, 
    directives: [ChildComponent] 
}) 
export class ParentComponent { 
    @ViewChild(ChildComponent) 
    private childComponent: ChildComponent; 

    save(): void { 
     this.myService.myHTTPCall().subscribe((event) => { 
      this.childComponent.waitingForHostedComp(event); 
     }) 
    } 

} 

你可以在Component Interaction Cookbook: Parent Calls a ViewChild看到更多详细信息。

+0

有趣的....将我的其他输入和输出工作(我没有引用,在这个代码示例中)像以前一样? – nottinhill

+1

当然,他们会像以前一样工作。 ViewChild只是在打字稿代码中与你进行交互的一种方式。 –

+0

我必须将'private childComponent:ChildComponent;'放入构造函数中,然后才能完美地工作。谢谢,贝尔纳多。 – nottinhill