Category / Section
How to add toggle button inside the DropDownButton popup
This knowledge base explains how to add toggle button inside the DropDownButton popup.
It can be achieved by using ‘beforeItemRender’ event and the toggle state of button can be changed using the ‘select’ event. By default, DropDownButton popup will be closed on item click and it has been prevented using ‘beforeClose’ event.
In the below code example, the toggle button ‘Log In/Log Out’ added inside DropDownButton popup and button toggle state is maintained while performing open/close popup.
app.component.html
<button ejs-dropdownbutton [items]="items" (beforeItemRender)="itemRender($event)" (select)="select($event)"(beforeClose)="beforeClose($event)" content="Account"></button>
app.component.ts
import { Component } from '@angular/core';
import { DropDownButtonComponent, ItemModel, MenuEventArgs } from '@syncfusion/ej2-ng-splitbuttons';
import { createElement } from '@syncfusion/ej2-base';
@Component({
selector: 'my-app',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
//DropDownButton items definition
public items: ItemModel[] = [
{
text: 'Dashboard',
},
{
text: 'Notifications',
},
{
text: 'User Settings',
},
{
text: 'Log In',
}];
public toggleElem: any = createElement('button', { className: 'e-btn', id: "loginBtnElem", innerHTML: "Log In", styles:"width:100%" });
public itemRender(args: MenuEventArgs) {
//To customize the item
if (args.item.text == "Log In") {
args.element.innerText = "";
args.element.appendChild(this.toggleElem);
}
}
public select(args: MenuEventArgs) {
// To change the button state and text on select
if (args.item.text == "Log In") {
args.element.children[0].classList.toggle('e-active');
if (args.element.children[0].classList.contains('e-active')) {
args.element.children[0].innerHTML = 'Log Out';
}
else {
args.element.children[0].innerHTML = 'Log In';
}
}
}
public beforeClose(args) {
//To prevent popup closing when item clicked
if (args.event.target.id == "loginBtnElem")
args.cancel = true;
else
this.toggleElem = document.getElementById("loginBtnElem").cloneNode(true);
}
}
Demo Sample: https://stackblitz.com/edit/angular-xphw2e
The following output displays the result of adding toggle button in DropDownButton popup.
