Add active class to submenu on click in angular 4
Clash Royale CLAN TAG#URR8PPP
Add active class to submenu on click in angular 4
I have created a nested menu in Angular 4. I am facing problem with active class. Here is my code.
My code
I am able to add active class to main link but what should I do to add active class to submenu based on click. Please help
On click of submenu clicked submenu should be active. what should I do for that
– vedankita kumbhar
Aug 8 at 6:52
1 Answer
1
You can make an object to store what is selected for main
link and sub
link and then apply the class accordingly.
main
sub
For example, you may pass main
as an argument to tell that it is a main link and check isActive
accordingly for main
itself.
main
isActive
main
(click)="select('main', n.name);" [ngClass]="active: isActive('main', n.name)"
Similarly, it can be done for the sub
link.
sub
Your functions could be as follows:-
select(type, item, $event)
this.selected[type] = (this.selected[type] === item ? null : item);
$event ? $event.stopPropagation() : null;
isActive(type, item)
return this.selected[type] === item;
You may stop propagation when selecting the sub link which is optional, I suppose (Kindly test for your use case).
Please check the code below:-
https://stackblitz.com/edit/angular-7b7cwd?file=src/app/app.component.html
Thank u so much @Ankit :)
– vedankita kumbhar
Aug 8 at 7:15
Glad that it helped. :)
– Ankit Sharma
Aug 8 at 7:15
There is one problem. Please check in this condition. click on one sub menu the open second main menu.
– vedankita kumbhar
Aug 8 at 7:17
That is because both sub menus have the same value as
Sub Menu 1
. Kindly try changing the values for the sub menus. I have changed it in the example for you. Please check now. You need to pass something else to identify it easily and correctly.– Ankit Sharma
Aug 8 at 7:21
Sub Menu 1
Ok thank you :) working fine
– vedankita kumbhar
Aug 8 at 7:24
By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.
Clicking on second menu and third menu shows the submenu...then what you want?
– Onkar
Aug 8 at 6:45