我有关于Angular 2的流行错误。当我从另一个组件调用函数时,我遇到了这个错误。
"Cannot read property 'onChange' of undefined at CD019.onChangeParent"
我的代码如下:
@ViewChild('testComponent') testComponent: CD020;
onChangeParent() {
this.testComponent.onChange;
}
和子组件是
@Output() childChanged = new EventEmitter<string>();
onChange(value: string, test: string) {
this.childChanged.emit(value);
this.Test(test);
}
感谢您的帮助。
答案 0 :(得分:1)
根据文档,您应使用组件类型作为ViewChild装饰器的标识符。 https://angular.io/docs/ts/latest/api/core/index/ViewChild-decorator.html
@ViewChild(CD020) testComponent: CD020;
答案 1 :(得分:0)
您需要确保@ViewChild(ChildType) testComponent: ChildType
使用相同类型的E.g.your子组件:
@Component({
selector: 'app-my-child',
templateUrl: './my-child.component.html',
styleUrls: ['./my-child.component.css']
})
export class CD020 implements OnInit {
ngOnInit() {
}
@Output() childChanged = new EventEmitter<string>();
onChange(value: string, test: string) {
this.childChanged.emit(value);
}
}
你的父母html:
<app-my-child></app-my-child> <!-- uses the template selector name -->
您的父代码:
//note the name inside the viewChild and the type of testComponent
@ViewChild(CD020) testComponent: CD020;
onChangeParent() {
// must pass two arguments.
this.testComponent.onChange("someValue","someTest");
}