How can I have conditional ion-back-button text based on if the defaultHref is used?

柔情痞子 提交于 2020-02-06 18:06:31

问题


I have a button that I want to display text but only when the defaultHref is used. Is there a way to detect that?

<ion-back-button *ngIf="defaultHref" [defaultHref]="defaultHref" [text]="text" icon="ios-arrow-back" mode="md"></ion-back-button>

If the back button shows as a result of a different router forward, the back button link goes somewhere else but the text I set is still there. Is there a way to make that text conditional upon the link matching the defaultHref that I set?


回答1:


From some investigation, the component itself doesn't know if it can go back until it tries to go back:

  private onClick = async (ev: Event) => {
    const nav = this.el.closest('ion-nav');
    ev.preventDefault();

    if (nav && await nav.canGoBack()) {
      return nav.pop({ skipIfBusy: true });
    }
    return openURL(this.defaultHref, ev, 'back');
  }

This is still possible though because you can just mimic this, and check if the app can go back in the logic that you use to set the text.

Page.html:

<ion-buttons slot="start">
  <ion-back-button defaultHref="/custom-back-button" [text]="getCustomText()"></ion-back-button>
</ion-buttons>

Page.ts:

  constructor(
    private ionRouterOutlet: IonRouterOutlet
  ) { }

  getCustomText():string {
    if(this.ionRouterOutlet.canGoBack()) {
      return "Can Go Back Text";
    } else {
      return "Can Only Go To Default";
    }
  }

Which shows this when it's navigated directly:

And this when it has a history to go back to:



来源:https://stackoverflow.com/questions/56999235/how-can-i-have-conditional-ion-back-button-text-based-on-if-the-defaulthref-is-u

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!