Ionic2: expanding menu options in the sidemenu

I'm not very familiar with ionic, but I have a question on behalf of my friend who is hesitant to ask on StackOverflow because she's unsure of how to frame her question.

She simply wants to learn how to implement a submenu in an ionic 2 side menu starter project.

The HTML

<ion-menu [content]="content" side="left" id="menu1">
  <ion-content class="outer-content" no-border-top>
    <ion-list lines (click)="openSubCat($event,category)">
      <ion-list-header>
        Shop For
      </ion-list-header>
      <ion-item *ngFor="let item of categoryArray" let idx=index (click)="openSubCat(item.value)">
        <ion-icon [name]="item.icon" item-left></ion-icon>
          {{ item.value }}
        <ion-icon [name]="item.icon2" item-right ></ion-icon>
     </ion-item>
    </ion-list>
 </ion-content>
</ion-menu>
<ion-nav [root]="rootPage" #content swipeBackEnabled="false"></ion-nav>`

the app-components.ts

import { Component, ViewChild } from '@angular/core';
import { Nav, Platform } from 'ionic-angular';
import { StatusBar, Splashscreen } from 'ionic-native';

import { TutorialPage } from '../pages/tutorial/tutorial';


@Component({
  templateUrl: 'app.html'
})
export class MyApp {
  @ViewChild(Nav) nav: Nav;

  rootPage: any = TutorialPage;

  pages: Array<{title: string, component: any}>;

  categoryArray: Array<any> = [{
      value:'Men',
      icon: 'man',
      icon2:'ios-arrow-forward-outline',
      view:'viewToGoTo'
   },{
      value:'Woman',
      icon: 'woman',
      icon2:'ios-arrow-forward-outline',
      view:'viewToGoTo'
   },{
      value:'Kids',
      icon: '',
      icon2:'ios-arrow-forward-outline',
      view:'viewToGoTo'
   }
   ];
  constructor(public platform: Platform) {
    this.initializeApp();
  }

  initializeApp() {
    this.platform.ready().then(() => {
      // Okay, so the platform is ready and our plugins are available.
      // Here you can do any higher level native things you might need.
      StatusBar.styleDefault();
      Splashscreen.hide();
    });
  }

  openPage(page) {
    // Reset the content nav to have just this page
    // we wouldn't want the back button to show in this scenario
    this.nav.setRoot(page.component);
  }

openSubCat(category){
  console.log(category)

}

}

I provided her with this link, but couldn't explain much as I don't have much experience with ionic. It seems that creating a dropdown requires a 2d array, is that correct? Could someone please enhance the code in this question by adding a submenu example for her learning?

Answer №1

Regarding the repository (by the way, thank you for sharing my demo lol), this is just one method to create a side menu in Ionic. As mentioned in the README.md file, start by copying the contents of the side-menu-content folder (including the .ts, .html, and .scss files) into your project.

Next, add it to the declarations array within your NgModule in the app.module.ts file:

// The path might vary on your setup
import { SideMenuContentComponent } from '../side-menu-content/side-menu-content.component';

@NgModule({
  declarations: [
    MyApp,
    // ...
    SideMenuContentComponent // <- Include here!
  ],
  imports: [
    BrowserModule,
    IonicModule.forRoot(MyApp)
  ],
  bootstrap: [IonicApp],
  entryComponents: [
    MyApp,
    // ...
  ],
  providers: [
    StatusBar,
    SplashScreen,
    { provide: ErrorHandler, useClass: IonicErrorHandler }
  ]
})
export class AppModule { }

Then, proceed to add code for initializing the side menu and handling selection actions. In the app.component.ts file, insert the following code:

@Component({
    templateUrl: 'app.html'
})
export class MyApp {
    @ViewChild(Nav) navCtrl: Nav;

    @ViewChild(SideMenuContentComponent) sideMenu: SideMenuContentComponent;

    public rootPage: any = HomePage;
    public options: Array<MenuOptionModel>;

    constructor(private platform: Platform,
                private statusBar: StatusBar,
                private splashScreen: SplashScreen,
                private menuCtrl: MenuController) {
        this.initializeApp();
    }

    initializeApp() {
        this.platform.ready().then(() => {          
            this.statusBar.styleDefault();
            this.splashScreen.hide();

            // Define the options
            this.options = this.getSideMenuOptions();
        });
    }

    private getSideMenuOptions(): Array<MenuOptionModel> {
        let menuOptions = new Array<MenuOptionModel>();

        // Populate the menu options

        return menuOptions;

    }

    public selectOption(option: MenuOptionModel): void {
        this.menuCtrl.close().then(() => {

            this.sideMenu.collapseAllOptions();

            this.navCtrl.push(option.component);
        });
    }

    public collapseMenuOptions(): void {
        this.sideMenu.collapseAllOptions();
    }
}

Finally, include the side menu in the view by adding the following to the app.html file:

<ion-menu persistent="true" [content]="content" (ionClose)="collapseMenuOptions()">
    <ion-header>
        <ion-toolbar color="secondary">
            <ion-title>Menu</ion-title>
        </ion-toolbar>
    </ion-header>

    <ion-content>

        <!-- Side Menu -->
        <side-menu-content [accordionMode]="true" [options]="options" (selectOption)="selectOption($event)"></side-menu-content>

    </ion-content>
</ion-menu>

<!-- Disable swipe-to-go-back because it's poor UX to combine STGB with side menus -->
<ion-nav [root]="rootPage" #content swipeBackEnabled="false"></ion-nav>

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

typescript exploring the versatility of dynamic types and generics

Understanding TypeScript dynamic and generic types can be challenging for me. The goal is to create a function that generates an object with a specific type, where some properties of the object must match the parameters provided to the function. Essentia ...

Is it possible to use square brackets in conjunction with the "this" keyword to access a class property using an expression?

export class AppComponent implements OnInit { userSubmitted = false; accountSubmitted = false; userForm!: FormGroup; ngOnInit(): void {} onSubmit(type: string): void { this[type + 'Submitted'] = true; if(this[type + 'For ...

Delete one item from a group of objects[]

In my TypeScript code, I have a declared object like this: public profileDataSource: { Value: string, Key: number }[]; This results in an object structure that looks similar to the following: 0: Object {Value: "<Select Profile>", Key: null} ...

Handle and manage errors within the controller in Express.js to prevent the further execution of asynchronous functions

Consider a scenario where there is an API endpoint /register, designed to register new users in an application. The function utilized is asynchronous, as an attempt is made to incorporate an asynchronous process within an AuthController when performing pas ...

The ng-change event fails to trigger when the date change event is activated

Hey there, I'm new to working with AngularJS. I have a scenario where I want a method to be triggered when I change the date, opening a modal. However, when I use the ng-change event, the method is not called upon date change. If I switch to using ng- ...

having trouble transferring data from one angular component to another

I've been attempting to send data from one component to another using the service file method. I've created two components - a login component and a home component. The goal is to pass data from the login component to the home component. In the l ...

Showcase pictures within an angular smart table

Is it possible to display images in a column within an ng smart table? We have several columns consisting mostly of data, with one column dedicated to displaying images. Following the ng smart table concept, I attempted to implement the code below which cu ...

Looking to resolve a module-specific error in Angular that has not been identified

While practicing Angular, I encountered an error during compilation: Module not found: Error: Can't resolve './app.component.css' in 'D:\hello-world-app\src\app' i 「wdm」: Failed to compile. This is my app.compo ...

Spring Boot app experiences issues with certain endpoints not functioning properly upon receiving requests from the Angular front end

My code includes the following endpoint: @PutMapping(path = "/like/{id}") public void likeQuestion(@PathVariable("id") String id, @Valid @NotNull @RequestBody Student student) { logger.info(id, student); questionService.likeQues ...

Creating dynamic attributes for hibernate mapping through front-end integration

Currently, I am facing the challenge of inserting JSON data into our database using a combination of Spring Boot, Hibernate, and Angular. The specific attribute name within this JSON data remains unknown during compile time. Is there a viable solution tha ...

The image map library functions seamlessly with React but encounters issues when integrated with Next.js

I have been working on a client project that requires the use of an image map. I searched for a suitable library, but struggled to find one that is easy to maintain. However, I came across this particular library that seemed promising. https://github.com/ ...

Having trouble sending correct true/false values for selected radio buttons on an Angular5 table, often requiring users to click them twice to submit the appropriate values

My goal is to assign true or false values to selected radio buttons in each row and then form an object for submission. To distinguish between the radio button values in each row, I have used {{k}}+{{sizeobj.rbSelected}} as the value which is causing issue ...

Find a string that matches an element in a list

I currently have a list structured like this let array = [ { url: 'url1'}, { url: 'url2/test', children: [{url: 'url2/test/test'}, {url: 'url2/test2/test'}], { url: 'url3', children: [{url: & ...

Are you harnessing the power of Ant Design's carousel next and previous pane methods with Typescript?

Currently, I have integrated Ant Design into my application as the design framework. One of the components it offers is the Carousel, which provides two methods for switching panes within the carousel. If you are interested in utilizing this feature using ...

selectize.js typescript: Unable to access values of an undefined object (reading '0')

I've been working on incorporating selectize.js into my project using webpack and typescript. After installing selectize.js and the necessary types, I added the following to my code: yarn add @selectize/selectize yarn add @types/select2 Within my c ...

Update all occurrences of a particular value to null within the Realtime Database using Firebase Cloud Functions

I need to update the values of a specific userID linked to multiple post keys in my database by setting the userID to null. The userIDs are associated with post keys located in the path: posts/ivies/userIDs in my database. Take a look at how the database i ...

Querying data elements using Graphql mutations: a step-by-step guide

const MUTATION_QUERY = gql` mutation MUTATION_QUERY( $name: bigint! ) { insert_name( objects: { name: $name } ) { returning { id name } } } `; const [onClick, { error, data }] = useMut ...

Initiating change notification when utilizing service communication

So I am facing an issue with two unrelated components where I am attempting to establish communication between them using a service and a BehaviorSubject. Despite successfully exchanging data, calling the service from one component does not trigger change ...

Troubleshooting a problem with Angular 2's ng-select component within a ReactiveForms when working with an array of

I am struggling to retrieve data for the ng-select component. <ng-select [allowClear]="true" [items]="tempArrayUoM[i]" formControlname="uom" [active]="initialUoM[i]" placeholder="UoM"> </ng-select> Could someone assist me in underst ...

I'm struggling to figure out the age calculation in my Angular 2 code. Every time I try to run it,

Can anyone assist me with calculating age from a given date in Angular? I have written the following code but I keep getting undefined in the expected field. This is Component 1 import { Component, OnInit, Input } from '@angular/core'; ...