调用嵌套组件函数angular2

时间:2016-08-01 13:20:39

标签: angular

想象一下这个主机组件代码:

@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)
  }

如何从Host-Component(Parent)调用waitingForHostedComp?

1 个答案:

答案 0 :(得分: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

中查看更多详情