【发布时间】:2019-04-03 02:00:42
【问题描述】:
父组件
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';
}
}
静态注入器出现错误,我无法在父组件中注入子组件。这是错误。
StaticInjectorError(AppModule)[AppComponent -> ChildComponent]: 静态注入器错误[子组件]: NullInjectorError: 没有 ChildComponet 的提供者!
我在 Appmodule 中添加了引用,并在声明中添加了组件。不过,我也面临同样的问题。
请帮忙!!
【问题讨论】:
-
使用@ViewChild 看看alligator.io/angular/viewchild-access-component
-
@Vikas 我用过同样的方法,但我收到了“预期声明”这个问题。当我尝试在组件中编写 @ViewChild('child') child:ChildCmp; 时出现错误。请帮忙!
-
@ViewChild('child') child:ChildCmp;你的类型在哪里ChildCmp??我看到ChildComponent不是ChildCmp。 -
@Developer 使用 rx js 主题。你可以试试我的方法。不推荐创建组件实例
-
@penleychan 是的,它的 ChildComponent 是我的错字。
标签: angular typescript