【问题标题】:how to call a method from html page to a class如何从html页面调用方法到类
【发布时间】:2020-01-14 04:04:35
【问题描述】:

我正在研究 IONIC,我正在尝试做一个“动态”侧边菜单。

我的问题是从侧面菜单“组件”中调用一个方法。 好吧,如果该方法位于与“HTML 文件”相关的“TS 文件”中,则调用它没有问题,例如 <ion-label (click)="onSearch()"> 但是方法 onSearch() 不在“TS 文件”中” 与“HTML 文件”相关。让我解释一下……

侧边菜单是这样制作的:

  • 在 app.component.html 中
<ion-app>
  <app-side-menu></app-side-menu>
  <ion-router-outlet id="mainContent" main></ion-router-outlet>
</ion-app>
  • 在 side-menu.html 组件中
<ion-menu slide="start" type="overlay" contentId="mainContent" menuId="slidingMenu1" id="slidingMenu1">

  <ion-header>
    <ion-toolbar color="primary">
      <ion-title>Menu</ion-title>
    </ion-toolbar>
  </ion-header>

  <ion-content>
    <ion-list>
      <ion-menu-toggle auto-hide="false">
        <ion-item>
          <ion-icon name="Search" color="primary" slot="start"></ion-icon>
          <ion-label (click)="onSearch()">
            Search
          </ion-label>
      </ion-menu-toggle>
    </ion-list>
  </ion-content>
</ion-menu>
  • 我有一个服务 CoreMenuService,它调用侧边菜单,如下所示:
constructor(public menu: MenuController) { }

 // Toggle the Menu1 and hide the one you do not need
  public toggleMenu1() {
    this.menu.enable(true, 'slidingMenu1');
    this.menu.toggle('slidingMenu1');
  • 然后在我需要的页面中调用侧边菜单:

HTML 文件

<ion-header>
    <ion-toolbar>
      <ion-buttons slot="start">
        <ion-button (click)="onOpenMenu()"><ion-icon name="menu"></ion-icon></ion-button>
      </ion-buttons>
      <ion-title>person</ion-title>
    </ion-toolbar>
  </ion-header>

  <ion-content>
    <p class="ion-padding">It's the Person page</p>
  </ion-content>

TS 文件,我想在其中使用侧面菜单触发的方法

export class PersonPage implements OnInit {

  constructor( public menu: CoreMenuService ) {}

  ngOnInit() {}

  onOpenMenu() {
    this.menu.toggleMenu();
  }

  onShare() {
    console.log('shared');
  }
}

那么如何使用侧面菜单组件中 PersonPage.ts, onShare() 中声明的方法呢?

我希望这对你来说很清楚,并且你理解我。 :)

如果您需要更好地理解,这里有源代码: Code

感谢您的帮助

【问题讨论】:

  • 我知道的唯一方法是在与您的侧边菜单组件相关的 TS 文件中添加一个函数,并让该函数从中调用所需的函数。
  • 如果两个组件需要onShare(),为什么不将它放在服务中并从组件中调用它。
  • 如果你想调用另一个组件的函数(正如@KiJéy 建议的那样),也可以看看这个:stackoverflow.com/questions/37587732/…
  • @Ki Jéy 是的,我也这么认为,但我不知道这样做,因为“PersonPage.ts”不是服务。因此,如果我这样称呼它let m = PersonPage.onShare();,它就行不通了。所以我尝试使用构造函数,它也不喜欢它,因为它不是服务。
  • @Ramesh onShare 就是一个例子,它可以是任何其他创建的方法。我正在尝试做一个动态幻灯片菜单,因此通过单击侧面菜单调用的方法可能会根据调用菜单的位置而有所不同。

标签: html angular typescript ionic-framework


【解决方案1】:

试试这个 在您的侧边菜单 component.ts 中,您可以执行以下操作:

import { PersonPage } from './../../pages/person/person.page';
export class SideMenuComponent implements OnInit , OnDestroy {
 onShare() {
  const personPage = new PersonPage(null);
  personPage.onShare();
}
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-01-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多