[英]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.