Advertisement
Guest User

Untitled

a guest
Feb 20th, 2017
88
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.20 KB | None | 0 0
  1. //高亮当前页面对应的目录
  2. import {
  3. Component,
  4. Directive,
  5. ElementRef,
  6. Renderer,
  7. Input,
  8. HostListener,
  9. OnInit,
  10. OnDestroy,
  11. AfterViewInit,
  12. } from '@angular/core';
  13.  
  14. /*
  15. * Directive
  16. */
  17. @Directive({
  18. selector: '[myToggle]' // using [ ] means selecting attributes
  19. })
  20. export class MyToggleDirective implements OnInit,OnDestroy,AfterViewInit{
  21. @Input() status: boolean = false;//目录默认展开状态,false:不展开,true:不展开,true
  22. @Input() disableclick: boolean = false;//一级目录是否可点击,false:可点击,true:不可点击
  23.  
  24. private height: string;
  25. private dom: any;
  26. private headerDom: any;
  27. private contentDom: any;
  28. private activeClass:string = 'active';
  29.  
  30. private listenFuncs:Array<any> = [];
  31.  
  32. constructor(
  33. public element: ElementRef,//使用ElementRef可以直接访问dom
  34. public renderer: Renderer//使用Renderer操作虚拟dom里的某一个元素
  35. ) {
  36.  
  37. }
  38.  
  39. public ngOnInit(){
  40. }
  41. public ngAfterViewInit(){//组件及子组件渲染结束执行
  42. this.dom = this.element.nativeElement;
  43. this.headerDom = this.element.nativeElement.querySelector('[mytoggleheader]');
  44. this.contentDom = this.element.nativeElement.querySelector('[mytogglecontent]');
  45.  
  46. this.height = window.getComputedStyle(this.contentDom).getPropertyValue('height');
  47. let style = this.renderer.createElement(this.element.nativeElement,'style');
  48.  
  49. let self = this;
  50. //不响应点击事件
  51. if(this.disableclick) return;
  52. else{
  53. this.listenFuncs.push(this.renderer.listen(this.headerDom,'click',(e) =>{self.toggle()}))
  54.  
  55. //初始化
  56. if(this.status) this.open();
  57. else this.close();
  58. }
  59. }
  60. toggle(){
  61. if(this.status){//已经打开的,关闭
  62. this.close();
  63. }else{//已经关闭的,打开
  64. this.open();
  65. }
  66. this.status = !this.status;
  67. }
  68. open(){
  69. this.renderer.setElementClass(this.dom,this.activeClass,true);
  70. this.renderer.setElementStyle(this.contentDom,'height',this.height);
  71. }
  72. close(){
  73. this.renderer.setElementClass(this.dom,this.activeClass,false);
  74. this.renderer.setElementStyle(this.contentDom,'height','0px');
  75. }
  76. ngOnDestroy(){
  77. this.listenFuncs.forEach((func)=>{func()});
  78. }
  79. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement