Create mnemonic ui in menuitem in Angular Menu component
12 Sep 20254 minutes to read
A mnemonic UI allows users to activate menu items using keyboard shortcuts by highlighting a specific character in the label. This is commonly achieved by underlining the character to indicate its mnemonic role.
This can be implemented using the beforeItemRender event by inserting a <u> tag around the target character and assigning the result to the innerHTML of the li element.
In the following example, the first character in the File, Open, and Save menu items is underlined.
import { NgModule } from '@angular/core'
import { BrowserModule } from '@angular/platform-browser'
import { MenuModule } from '@syncfusion/ej2-angular-navigations'
import { Component } from '@angular/core';
import { enableRipple } from '@syncfusion/ej2-base';
import { MenuItemModel, MenuEventArgs } from '@syncfusion/ej2-angular-navigations';
enableRipple(true);
@Component({
imports: [ MenuModule],
standalone: true,
    selector: 'app-root',
    template: `<div class="e-section-control">
                <ejs-menu #menu [items]='menuItems' (beforeItemRender)='beforeItemRender($event)'></ejs-menu></div>`
})
export class AppComponent {
    public menuItems: MenuItemModel[] = [
        {
            text: 'File',
            iconCss: 'em-icons e-file',
            items: [
                { text: 'Open', iconCss: 'em-icons e-open' },
                { text: 'Save', iconCss: 'e-icons e-save' },
                { separator: true },
                { text: 'Exit' }
            ]
        },
        {
            text: 'Edit',
            iconCss: 'em-icons e-edit',
            items: [
                { text: 'Cut', iconCss: 'em-icons e-cut' },
                { text: 'Copy', iconCss: 'em-icons e-copy' },
                { text: 'Paste', iconCss: 'em-icons e-paste' }
            ]
        },
        { text: 'Format' },
        { text: 'View' },
        { text: 'Bookmarks' },
        { text: 'Tools' },
        { separator: true },
        { text: 'Help' }
    ];
    public beforeItemRender(args: MenuEventArgs): void {
        if (['File', 'Open', 'Save'].indexOf(args.item.text as string ) > -1) {
            // To underline a First character.
            let underlinedText: string = '<u>' + (args.item.text as string).slice(0, 1) + '</u>' + (args.item.text as string).slice(1);
            args.element.innerHTML = args.element.innerHTML.replace(args.item.text as string, underlinedText);
        }
    }
}import { bootstrapApplication } from '@angular/platform-browser';
import { AppComponent } from './app.component';
import 'zone.js';
bootstrapApplication(AppComponent).catch((err) => console.error(err));