调用嵌套组件函数angular2

mes*_*lds 2 angular

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

@Component({
    directives: [nestedComponentDirective]
})

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

现在嵌套组件:

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


export class ContinuationCheckDirective {
  @Input() waitingForHostedComp(value) {
    console.log ("value", value)
  }
Run Code Online (Sandbox Code Playgroud)

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

Ber*_*eco 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);
        })
  }

}
Run Code Online (Sandbox Code Playgroud)

您可以在组件交互手册中查看更多详细信息:父级调用ViewChild.