Search code examples
angularionic-frameworkroutesangular-structural-directive

Angular - Hide Ionic Tab Bar component when clicked on different route (Product Details Page)


I am attempting to hide an ionic tab bar when I click on an product item thats redirected to the product details page. I've attempted to use other lifecycle methods such as ngAfterViewInit(), ngAfterViewChecked(), even tried to setTimeOut(). Currently using a structural directive ngIf(), to hide the component, but it hides for all routes, not the one specified. I've tried to render it conditionally as well, but breaks the code completely.

app.componet.ts:

 @Component({
  template: `
    <app-tabbar> *ngIf="showComponent"></app-tabbar>
    <router-outlet></router-outlet>
  `,
})
export class AppComponent {
  showComponent: boolean = false;

  constructor(private router: Router) {
    this.router.events.forEach((event) => {
      if (event instanceof RoutesRecognized) {
        this.showComponent = true;
        console.log('URL', event.url);
        if (event.url.startsWith('/product/')) {
          console.log(' tabbar does show');
          this.showComponent = false;
        }
      }
    });
  }

app.component.html:

  <div *ngIf="showComponent" class="showComponent">
    <app-tabbar></app-tabbar>
  </div>

Might also be worth mentioning that when the page breaks I get an error, that I've never seen before. It seems as thought I'm trying to hide the Tab Bar before the DOM even has access to it.

Error:

product.resolver.ts:27 ERROR Error: Uncaught (in promise): TypeError: Cannot read properties of undefined (reading 'appendChild')

I'm wondering if it has to do with the navigation as a whole.

My thought is that instead of just having all the screens listed as children under the TabnavPage, we could put a path to the PDP outside, nestled between the path: 'tab-nav' and path: '' objects.

I've also saw a website that suggested creating a promise, resolving it immediately, and adding a handler with then() which would run on the next tick.  but that's probably functionally equivalent to setTimeout(0) so maybe won't help.


Solution

  • Had the same need in my app. I use css property display and Ionic life cycle ionViewWillEnter / ionViewWillLeave.

    TS FILE of the page where you need to hide

    ionViewWillEnter() {
    
    const tabBar = document.getElementById('app-tab-bar');
    if (tabBar !== null) {
      tabBar.style.display = 'none';
    }
    
    }
    
     ionViewWillLeave() {
    
    const tabBar = document.getElementById('app-tab-bar');
    if (tabBar !== null) {
      tabBar.style.display = 'flex';
    }
    }
    

    HTML File of the tab bar

    <ion-tabs >
      <ion-tab-bar slot="bottom" color="primary" id="app-tab-bar">
        // content of your tab bar
      </ion-tab-bar>
    
    </ion-tabs>