无法在角度6中从父级到子级访问方法

时间:2019-10-29 05:58:51

标签: angular angular6

我无法获取另一种父方法,该方法在我用作输入并调用子组件的父方法中调用。

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
.
.
.

2 个答案:

答案 0 :(得分:1)

当您从子组件中调用父方法时,ferchChilderForPage中的此上下文将引用子组件

示例

fetchChildrenForPage(page, pagePerPage){
    console.log(page, pagePerPage, this); //this will refer to child component When you call from child
   //  this.createTest('ClusterInfo');
  }

尝试

将父实例传递给子组件,然后从子组件中调用父方法

parent.component.html

<app-demo [appInstance]="this"></app-demo>

parent.component.html

export class DemoComponent implements OnInit {
  @Input() appInstance;
  constructor() { }

  ngOnInit() {
  }

  onClick(){

    this.appInstance.fetchChildrenForPage('demo','demo2');
  }

}

使用ViewChid从子级访问父级组件实例

Example

答案 1 :(得分:0)

您正在fetchChildrenForPage中调用SubCustomPaginationComponent函数,但没有对我有意义的createTest函数。 尝试删除createTest函数,仅使用console.log或在CreateTest中定义SubCustomPaginationComponent函数