[英]Not able to access method from parent to child in angular 6
我无法获取另一个父方法,该方法在我用作输入并在子组件中调用的父方法中调用。
export class TreeMapComponent {
data;
constructor(public dialog: MatDialog, private router: Router) { }
ngOnInit() {
let results=[1,2,3]
}
fetchChildrenForPage(page, pagePerPage) {
let results={soemthing: 898, children: [1,2,3,3,4,5,6,7,8,8,8,5,3,3,4]}
this.data = { ...results, children: results.children.slice(1, 5) };
this.createTest(this.data);
}
createTest(clusterInfo): void{
console.log(clusterInfo)
}
}
TreeMapComponent.html(我用于上述组件的html,粗略的想法)
<app-sub-custom-pagination[fetchChildrenForPage]="fetchChildrenForPage">
</app-sub-custom-pagination>
现在我将提到子组件app-sub-custom-pagination
export class SubCustomPaginationComponent implements OnInit {
@Input()
fetchChildrenForPage;
currentPage;
constructor() { }
ngOnInit() {
selectPage(0);
}
selectPage(index): void {
this.currentPage = (index + 1);
this.fetchChildrenForPage(this.currentPage, this.quantityPerPage);
}
但不幸的是,我收到了一个错误:
ERROR TypeError: this.createTest is not a function
.
.
.
当您从子组件调用父方法时, ferchChilderForPage 中的 this 上下文将引用子组件
例子
fetchChildrenForPage(page, pagePerPage){
console.log(page, pagePerPage, this); //this will refer to child component When you call from child
// this.createTest('ClusterInfo');
}
尝试这个
将父实例传递给子组件,然后从子组件调用父方法
父组件.html
<app-demo [appInstance]="this"></app-demo>
父组件.html
export class DemoComponent implements OnInit {
@Input() appInstance;
constructor() { }
ngOnInit() {
}
onClick(){
this.appInstance.fetchChildrenForPage('demo','demo2');
}
}
或者
使用ViewChid从子访问父组件实例
您在 SubCustomPaginationComponent 中调用fetchChildrenForPage
SubCustomPaginationComponent
它没有createTest
function 这对我来说很有意义。 尝试删除createTest
Function 并使用 console.log 或在 SubCustomPaginationComponent 中定义CreateTest
SubCustomPaginationComponent
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.