Angular 10集成circular-menu实现环形菜单及CMenu无法识别解决方案
解决方案
步骤1:声明全局变量解决类型识别问题
TypeScript默认无法识别挂载在全局window对象上的CMenu和$变量,需要在cir-comp.component.ts的所有import语句下方添加全局变量声明:
declare var CMenu: any; declare var $: any;
步骤2:编写组件逻辑
环形菜单需要等组件视图渲染完成后再初始化,因此所有逻辑要写在ngAfterViewInit生命周期钩子中,同时组件销毁时需要解绑全局事件避免内存泄漏,完整组件TS代码如下:
import { Component, AfterViewInit, OnDestroy } from '@angular/core'; // 声明全局变量 declare var CMenu: any; declare var $: any; @Component({ selector: 'app-cir-comp', templateUrl: './cir-comp.component.html', styleUrls: ['./cir-comp.component.css'] }) export class CirCompComponent implements AfterViewInit, OnDestroy { menu: any; ngAfterViewInit(): void { // 初始化环形菜单 this.menu = CMenu("#menu1") .config({ menus: [{ title: "GitHub", icon: "fa fa-github", href: { url: "http://github.com", blank: true } }, { title: "GitLab", icon: ["fa fa-gitlab", '#4078c0'], }, { title: "subMenu", icon: "my-icon icon1", menus: [{ title: 'subMenu1', icon: 'fa fa-firefox' }, { title: 'subMenu2', icon: 'fa fa-file' }] }, { title: "subMenu", icon: "my-icon icon2" }, { title: "click", icon: "my-icon icon3" }, { title: "hash-href", href: "#someHash" }, { title: "clickMe!", click: function() { alert('click event callback'); } }, { disabled: true, title: "disabled" }] }); // 绑定全局点击和右键事件 $(document).click(() => { this.menu.hide(); }); $(document).contextmenu((e: any) => { this.menu.show([e.pageX, e.pageY]); return false; }); } ngOnDestroy(): void { // 组件销毁时解绑全局事件 $(document).off('click'); $(document).off('contextmenu'); } }
步骤3:编写组件模板
将示例HTML写入cir-comp.component.html文件:
<div class="tips"> Right click in page. </div> <div id="menu1" class="menu1"> </div>
步骤4:编写组件样式
将示例CSS写入cir-comp.component.css文件:
.tips { font-size: 40px; color: #999; position: fixed; top: 50%; left: 30%; } .menu1 { left: 50%; top: 50%; } .my-icon { background: url("https://rawgit.com/yandongCoder/circular-menu/master/examples/circular-menu.png"); } .icon1 { background-position: 0 0; } .icon2 { background-position: 0 -56px; } .icon3 { background-position: 0 -116px; }
注意事项
- 若使用font-awesome图标,需要自行安装对应依赖并在
angular.json的styles数组中引入font-awesome的CSS文件 - 可根据需求将全局事件绑定修改为组件宿主元素绑定,避免影响其他页面逻辑
- 需在父组件模板中添加
<app-cir-comp></app-cir-comp>标签才能渲染该组件
内容的提问来源于stack exchange,提问作者ab1004
相关产品推荐
相关产品推荐

