Tri*_*hak 1 typescript angular
父组件
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();
}
}
Run Code Online (Sandbox Code Playgroud)
子组件
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';
}
}
Run Code Online (Sandbox Code Playgroud)
我在使用静态注入器时遇到错误,无法在父组件中注入子组件。这是错误。
StaticInjectorError(AppModule)[AppComponent-> ChildComponent]:StaticInjectorError [ChildComponet]:NullInjectorError:没有为ChildComponet提供程序!
我在Appmodule中添加了引用,并在声明中添加了组件。不过,我也面临着同样的问题。
请帮忙!!
更新:
只需将like导出为子对象
<app-child #child></app-child>
,然后可以使用child
like 调用所有方法:<button> (click)="child.callMethod()">Call</button>
Parent.html
Run Code Online (Sandbox Code Playgroud)<app-child #child></app-child> <button (click)="child.callMethod()">Call</button>
旧答案
您可以@ViewChild
像以下示例一样由Parent 使用:
父级
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();
}
}
Run Code Online (Sandbox Code Playgroud)
儿童:
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++;
}
}
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
5300 次 |
最近记录: |