As professional Angular developers sometimes we come across unconventional requirements. One such requirement is to override the browser’s right-click context menu and provide a custom context menu.
There are a few ways to approach this requirement. One way is to use Angular CDK. A great article on this can be found here.
Another way is to leverage the contextmenu event of HTML elements. This event is supported by all major browsers as can be seen below from MDN documentation. This is the approach we will take in this article.
Browser support for contextmenu event
This approaches’ simplicity comes from the fact that we just need the understanding of Angular’s parent-child communication to achieve our objective.
The contextmenu event is handled on the div with class element. Notice the false after the event handler method call. This is important as it prevents the default right click browser context menu from opening.
The AppContextMenu component is embedded as a child component with conditional rendering using *ngIf. Eventually, this component will be rendered when the user right-clicks on the div with class element.
Notice the way in which the rightClickMenuItems property is set. It’s an array of type ContextMenuModel which allows us to configure different menu texts and corresponding events. Later these events are emitted back to the parent component when the user clicks an item on the context menu.
To display the context menu at right click position we have extracted the clientX and clientY properties of the contextmenu event object. These are later leveraged in getRightClickMenuStyle method and hooked up to AppContextMenu component using ngStyle.
Now, let’s have a look at the context-menu component template.
<ng-container>
<div
class="menu-link"
*ngFor="let menuItem of contextMenuItems; index as i"
(click)="onContextMenuClick($event, menuItem.menuEvent)">
{{ menuItem.menuText }}
<hr *ngIf="i < contextMenuItems.length - 1" />
</div>
</ng-container>
It loops over the input property contextMenuItemsto generate a list of menu links using *ngFor. Note how the click event handler is passing the event menuItem.menuEvent that needs to be raised based on the input data received from the parent.
The ContextMenuComponent class consists of just an input and an output properties.
import { Component, Input, Output, EventEmitter } from "@angular/core";
import { ContextMenuModel } from "../Interfaces/context-menu-model";
@Component({
selector: "app-context-menu",
templateUrl: "./context-menu.component.html",
styleUrls: ["./context-menu.component.css"],
})
export class ContextMenuComponent {
@Input()
contextMenuItems: Array<ContextMenuModel>;
@Output()
onContextMenuItemClick: EventEmitter<any> = new EventEmitter<any>();
onContextMenuClick(event, data): any {
this.onContextMenuItemClick.emit({
event,
data,
});
}
}
In a sense, it is a perfect dumb component and hence best for reusability! The parent component has complete control over the way it wants to use the context menu.
Based on the user’s selection on the custom context menu, the handler method emits output events with appropriate data. Now it’s up to the parent to handle the events the way it is supposed to based on the use case. For simplicity, we are just console logging here.
Before we wrap up, let’s discuss how we can close the context menu.
It’s fairly simple. A document click event listener has been set up on the AppComponentthat sets the isDisplayContextMenu flag to false.
And that’s it! We now have an extremely simple yet reusable custom context menu using only the basics of Angular.
Charts helps us to visualize large amount of data in an easy to understand and interactive way. This helps businesses to grow more by taking important decisions from the data. For example, e-commerce can have charts or reports for product sales, with various categories like product type, year, etc. In angular, we have various charting libraries to create charts. Ngx-charts is one of them. Check out the list of best angular chart libraries . In this article, we will see data visualization with ngx-charts and how to use ngx-charts in angular application ? We will see, How to install ngx-charts in angular ? Create a vertical bar chart Create a pie chart, advanced pie chart and pie chart grid Introduction ngx-charts is an open-source and declarative charting framework for angular2+. It is maintained by Swimlane . It is using Angular to render and animate the SVG elements with all of its binding and speed goodness and uses d3 for the excellent math functio...
forRoot / forChild is a pattern for singleton services that most of us know from routing. Routing is actually the main use case for it and as it is not commonly used outside of it, I wouldn’t be surprised if most Angular developers haven’t given it a second thought. However, as the official Angular documentation puts it: “Understanding how forRoot() works to make sure a service is a singleton will inform your development at a deeper level.” So let’s go. Providers & Injectors Angular comes with a dependency injection (DI) mechanism. When a component depends on a service, you don’t manually create an instance of the service. You inject the service and the dependency injection system takes care of providing an instance. import { Component, OnInit } from '@angular/core'; import { TestService } from 'src/app/services/test.service'; @Component({ selector: 'app-test', templateUrl: './test.component.html', styleUrls: ['./test.compon...
During the automation of multiple tasks on my job and personal projects, i decided to move on Puppeteer instead of the old school PhantomJS. One of the most usual problems with pages that contain a lot of content, because of the ads, images etc. is the load time, an exception is thrown (specifically the TimeoutError) after a page takes more than 30000ms (30 seconds) to load totally. To solve this problem, you will have 2 options, either to increase this timeout in the configuration or remove it at all. Personally, i prefer to remove the limit as i know that the pages that i work with will end up loading someday. In this article, i'll explain you briefly 2 ways to bypass this limitation. A. Globally on the tab The option that i prefer, as i browse multiple pages in the same tab, is to remove the timeout limit on the tab that i use to browse. For example, to remove the limit you should add: await page . setDefaultNavigationTimeout ( 0 ) ; COPY SNIPPET The setDefaultNav...
Comments
Post a Comment