我在标题部分工作,需要使用Angular6进行菜单的打开和关闭功能。
我找不到在其他地方但在某些组件上没有发生的click事件上触发功能的任何方法。因此,我致力于在angular js中使用javascript进行此类功能。我有以下代码可以做到这一点。
export class HeaderComponent implements OnInit, AfterViewInit {
menus : any;
activeLang : string;
// flag for menu closed or not
isMenuClosed : any;
constructor(private router : Router) {
this.isMenuClosed = true;
// assign this object to newInstance so that it can be used inside javascript function
let newInstance = this;
// function whenever click event occured
document.addEventListener("click", function(event){
// check if event.target.getAttribute('class') is true of not
// unfortunetly this line shows error event.target.getAttribute property doesnot exists ...
// getAttribute is not property its function
// I also try (event.target as HTMLInputElement).getAttribute()
if(!!event.target.getAttribute('class'))
{
let eventClass = event.target.getAttribute('class');
// confirm if click has been occured out of menu
if(!eventClass.includes("ti-close") &&
!eventClass.includes("nav-toggler") &&
!eventClass.includes("left-sidebar") &&
!eventClass.includes("scroll-sidebar") &&
!eventClass.includes("sidebar-nav") &&
!eventClass.includes("sidebarnav"))
{
newInstance.hideSideBar();
}
}
else
{
newInstance.hideSideBar();
}
});
hideSideBar()
{
let classString = document.getElementsByTagName('body')[0].getAttribute('class');
classString = classString.replace(" show-sidebar","");
document.getElementsByTagName('body')[0].setAttribute('class',classString);
this.isMenuClosed = true;
}
}
如果服务器没有启动但每当ng serve -o
命令被触发并且整个过程都停留在说错误的状态时,这是完美的工作。在终端中,它显示error TS2339: Property 'getAttribute' does not exist on type 'EventTarget'
我尝试try{}catch(e){}
,(event.target as HTMLInputElement).getAttribute('class')
,event.target.hasOwnProperty('getAttribute')
无效。那里是什么问题。
还有其他获取功能的方法。