无法在 angular 6 中从父到子访问方法

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

你在 SubCustomPaginationComponent 中调用 fetchChildrenForPage 函数,它没有对我有意义的 createTest 函数。 尝试删除 createTest 函数并仅使用 console.log 或在 SubCustomPaginationComponent

中定义 CreateTest 函数

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

例子

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