在Angular 6中无法从父组件访问子组件的方法。
在Angular 6中无法从父组件访问子组件的方法。
我无法获取父组件中在我正在使用和调用的父方法的另一种方法。\n
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) } }
\nTreeMapComponent.html(我用于上述组件的HTML,大致的想法)\n
\n现在我将提到子组件app-sub-custom-pagination
\n
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); }
\n但不幸的是,我得到了一个错误:\n
错误类型:this.createTest不是一个函数 。 。 。
在Angular 6中无法从父组件访问子组件的方法的问题可能是由于以下原因导致的:
- 在SubCustomPaginationComponent
中调用了fetchChildrenForPage
函数,但它并没有createTest
函数。解决方法是移除createTest
函数,只使用console.log或在SubCustomPaginationComponent
中定义CreateTest
函数。
- 问题的核心是fetchChildrenForPage
方法中包含了另一个属于同一个父组件的方法。而fetchChildrenForPage
方法中使用了this
关键字,而在这种情况下,this
指向的是SubCustomPaginationComponent
,而不是其父组件。因此,SubCustomPaginationComponent
中并没有这个方法。
解决这个问题的方法可能是需要重新考虑如何获取父组件的方法。实际上,this.chartTest()
方法包含了很多来自父组件的方法。
在Angular 6中,当你从子组件调用父组件的方法时,ferchChilderForPage中的this上下文将指向子组件。
解决方法有两种:
1. 传递父组件实例给子组件,然后从子组件调用父组件的方法。
父组件的HTML模板:
父组件的代码:
export class DemoComponent implements OnInit { appInstance; constructor() { } ngOnInit() { } onClick() { this.appInstance.fetchChildrenForPage('demo', 'demo2'); } }
2. 使用ViewChild来从子组件中访问父组件的实例。
示例:
export class DemoComponent implements OnInit { @ViewChild(AppDemoComponent) appDemoComponent: AppDemoComponent; constructor() { } ngOnInit() { } onClick() { this.appDemoComponent.fetchChildrenForPage('demo', 'demo2'); } }
以上两种方法都可以解决在Angular 6中无法从父组件访问子组件的方法的问题。