首页 > 解决方案 > Angular 6 - 使用子组件中的函数

问题描述

我正在编写一个应用程序,我的问题出在Angular 6Ionic 框架中。

我有一个带有 4 个子“页面”(组件)的父组件。我想调用scrollToTop()子组件中的函数,将页面滚动到顶部。

TabsPage 提供 4 个按钮(例如在 Instagram 上,您可以在应用程序中导航)。

父组件:

import { Component, ViewChild } from '@angular/core';
import { Tab1Page } from '../tab1/tab1.page';
import { Tab2Page } from '../tab2/tab2.page';
import { Tab3Page } from '../tab3/tab3.page';

@Component({
  selector: 'app-tabs',
  templateUrl: 'tabs.page.html',
  styleUrls: ['tabs.page.scss'],
})
export class TabsPage {
  @ViewChild(Tab1Page) tab1: Tab1Page;
  @ViewChild(Tab2Page) tab2: Tab2Page;
  @ViewChild(Tab3Page) tab3: Tab3Page;

  up2(){
    this.tab2.scroll2();
  }

  up3(){
    this.tab3.scroll3();
  }

HTML:

<ion-tabs>

    <ion-tab-bar slot="bottom">
        <ion-tab-button tab="tab1" (click)='up1()'>
            <ion-label>Tab1</ion-label>
        </ion-tab-button>

        <ion-tab-button tab="tab2" (click)='up2()'>
            <ion-label>Tab2</ion-label>
        </ion-tab-button>

        <ion-tab-button tab="tab3" (click)='up3()'>
            <ion-label>Tab3</ion-label>
        </ion-tab-button>

        <ion-tab-button tab="tab4" (click)='up4()'>
            <ion-label>Tab 4</ion-label>
        </ion-tab-button>

    </ion-tab-bar>

</ion-tabs>

子组件(Tab3):

import { Component, ViewChild } from '@angular/core';
import { IonContent } from '@ionic/angular';

@Component({
  selector: 'app-tab3',
  templateUrl: 'tab3.page.html',
  styleUrls: ['tab3.page.scss']
})
export class Tab3Page {
  @ViewChild(IonContent) content: IonContent;

  scroll3(){
    this.content.scrollToTop(0);
  }
}

这是错误代码:

错误类型错误:无法读取未定义的属性“scroll3”

标签: javascriptangularfunctionionic-framework

解决方案


推荐阅读