typescript - Cómo llamar al método de los componentes hijos desde el componente padre en Angular 6
Componente Padre
import { Component } from '@angular/core';
import { ChildComponent } from './notify.component';
@Component({
selector: 'my-app',
template:
`
<button (click)="submit()">Call Child Component Method</button>
`
})
export class AppComponent {
constructor(private childComp: ChildComponent) {
}
submit(): void {
// execute child component method
// This line is compiled properly but at the run time it gives me error related to the static injector## Heading ##
childComp.callMethod();
}
}
Componente hijo
import { Component, OnInit } from '@angular/core';
@Component({
selector: 'child',
template: '<h3>Child component {{test}}</h3>'
})
export class ChildComponent implements OnInit {
test:string;
constructor() { }
ngOnInit() { }
callMethod(): void {
console.log('successfully executed.');
this.test = 'Me';
}
}
Estoy recibiendo un error para el inyector estático, no puedo inyectar el componente hijo en el componente padre. Aquí está el error.
StaticInjectorError(AppModule)[AppComponent -> ChildComponent]: StaticInjectorError[ChildComponet]: NullInjectorError: ¡No hay proveedor para ChildComponet!
He agregado la referencia en el Appmodule y añadido el componente en la declaración. Aún así, sigo enfrentando el mismo problema.
¡Por favor, ayuda!
Respuesta #1
Actualización:
simplemente exporta el hijo como
<app-child #child></app-child>y luego puedes llamar a todos los métodos usandochildasí:<button> (click)="child.callMethod()">Llamar</button>Parent.html
<app-child #child></app-child> <button (click)="child.callMethod()">Call</button>
Respuesta antigua
Puedes usar @ViewChild desde el Padre como en el ejemplo:
Padre
import { Component, ViewChild } from '@angular/core';
import { ChildComponent } from './child.component';
@Component({
selector: 'my-app',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
constructor() { }
@ViewChild(ChildComponent) private myChild: ChildComponent;
submit() {
this.myChild.callMethod();
}
}
Niño:
import { Component } from '@angular/core';
@Component({
selector: 'child',
template: `<h3>Child component {{test}}</h3>`
})
export class ChildComponent {
test = 0;
callMethod() {
console.log('successfully executed.');
this.test++;
}
}
Aquí hay un ejemplo resuelto
