如何在Angular 6中从父组件调用子组件的方法 [英] How to call child components's method from the parent component in Angular 6
问题描述
父项
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();
}
}
子组件
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';
}
}
我在使用静态注入器时遇到错误,无法将子组件注入到父组件中.这是错误.
I am getting an error for the static injector, I am not able to inject the child component in the parent component. Here is the error.
StaticInjectorError(AppModule)[AppComponent-> ChildComponent]: StaticInjectorError [ChildComponet]: NullInjectorError:没有为ChildComponet提供程序!
StaticInjectorError(AppModule)[AppComponent -> ChildComponent]: StaticInjectorError[ChildComponet]: NullInjectorError: No provider for ChildComponet!
我在Appmodule中添加了引用,并在声明中添加了组件.不过,我也面临着同样的问题.
I have added the reference in the Appmodule and added the component in the declaration. Still, I am facing the same issue.
请帮助!
推荐答案
更新:
只需像<app-child #child></app-child>
那样导出子项,然后
您可以使用child
调用所有方法,例如:<button> (click)="child.callMethod()">Call</button>
just export the child like <app-child #child></app-child>
and then
you can call all methods using child
like : <button> (click)="child.callMethod()">Call</button>
Parent.html
<app-child #child></app-child>
<button (click)="child.callMethod()">Call</button>
旧答案
您可以像示例中那样使用Parent的@ViewChild
:
You can use @ViewChild
by Parent like in example:
父母
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();
}
}
孩子:
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++;
}
}
Here is a worked example
这篇关于如何在Angular 6中从父组件调用子组件的方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!