Introduction
The Ionic CLI start
command has a number of options for starter projects, even all the way back to Ionic 1.
You can see a list of them by using the following flag:
ionic start --list
One of these premade options is sidemenu
:
ionic start myApp sidemenu
Now, that’s great, you start with a side menu implemented. But what if you choose another option like tabs
or blank
? How do we then properly add a side menu later on? (It is likely you will add a side menu later on.)
ion-menu
Enter <ion-menu>
. The
But where should we put it?
app.component.html
The main app component files can be found in src/app
of the project. Our app.component.html
markup could look something like this, as you are probably using a router:
<ion-app>
<ion-router-outlet id="content"></ion-router-outlet>
</ion-app>
Properties
It is important we set a couple properties on <ion-menu>
. The most important is contentId
. This needs to match up to the id
of the main content. In our case, the router outlet is the main content.
<ion-app>
<ion-router-outlet id="content"></ion-router-outlet>
<ion-menu contentId="content">
</ion-menu>
</ion-app>
The second property is side
. This informs Ionic as to which side the side menu should be, end
or start
. It will default to start
.
Adding Menu Items
Let’s add some more markup - a header, a clickable item, etc.
<ion-app>
<ion-router-outlet id="content"></ion-router-outlet>
<ion-menu side="start" menuId="first" contentId="content">
<ion-header>
<ion-toolbar>
<ion-title>
Cronster
</ion-title>
</ion-toolbar>
</ion-header>
<ion-content>
<ion-list>
<ion-menu-toggle>
<ion-item button (click)="logout()">
<ion-icon name="exit-outline" slot="start"></ion-icon>
<ion-label>Logout</ion-label>
</ion-item>
</ion-menu-toggle>
</ion-list>
</ion-content>
</ion-menu>
</ion-app>
As you can see we have wrapped the <ion-item>
in a <ion-menu-toggle>
. This is so the menu will close upon clicking the item. This is nice, as we would have to figure out how to slide the menu back programmatically.
Conclusion
Adding a side menu in Ionic 6 (or any version for that matter) is pretty straight forward. There is a couple small details however that can cause confusion and lost time if ignored. But if we make sure we correctly set the contentId
, and use <ion-menu-toggle>
for our clickable items, we will be all set.