Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Angular如何自定义指令 #75

Open
deepthan opened this issue Jul 27, 2020 · 0 comments
Open

Angular如何自定义指令 #75

deepthan opened this issue Jul 27, 2020 · 0 comments

Comments

@deepthan
Copy link
Owner

自定义指令

做一个点击图片放大至全屏,再点击缩小的效果。

其实就是给这个元素动态添加和移除calss。

html

<div imageEnlarged class='image-default'>
    <div class='img-wrap'>
        <img src='../../../../assets/images/demo.jpg' alt='demo图片'>
    </div>
</div>
css
<!-- 小的图片 -->
.image-default {
    position: relative;
    width: 500px;
    margin: 2.4em 1em;
    img{
        width: 100%;
    }
    transition: all .3s ease-out; 
}

<!-- 全屏图片, 并且图片水平垂直居中 -->
.image-enlarged{
    height: 100%;
    width: 100%;
    background:#222222;
    
    position: fixed;
    z-index: 99999;
    left: 0px;
    top: 0px;

    display: table;
    overflow: hidden;
    
    transition: all .3s ease-in;
    
    .img-wrap{
        width: 100%;
        height: 100%;
        
        text-align: center;
        display: table-cell;
        vertical-align: middle;
    }
    img{
        max-height: 80%;
        max-width: 80%;
    }
}

法1: host里操作class


import { Directive, ElementRef, Renderer2 } from '@angular/core';

@Directive({
    selector: '[imageEnlarged]',
    host : {
        '[class.image-enlarged]' : 'toggle',
        '[class.image-default]' : '!toggle',
        '(click)' : 'clickImg()'
    }
})

export class ImageDirective {
    toggle: boolean = false;
    clickImg(){
      this.toggle = !this.toggle;
    }
}

法2: 操作dom元素

import { Directive, ElementRef, Renderer2 } from '@angular/core';

@Directive({
  selector: '[imageEnlarged]',
  host : {
    '(click)' : 'clickImg()'
    }
})
export class ImageDirective {
    toggle : boolean = false;
    classArr = ['image-enlarged', "image-default"];
    
    constructor(private el: ElementRef, private renderer: Renderer2) {}
    
    clickImg(){
        this.toggle = !this.toggle;
        this.toggle 
            ? this.toggleClass(this.classArr[0], this.classArr[1])
            : this.toggleClass(this.classArr[1], this.classArr[0])
        }
    }
    
    toggleClass(increase, decrease){
        this.renderer.addClass(this.el.nativeElement, increase);
        this.renderer.removeClass(this.el.nativeElement, decrease);
    }   
}

自定义指令如何传递参数

html

<div myDirective [disabled]="true"></div>

directive

@Directive({
  selector: '[myDirective]',
})
export class BtnToggleStatusDirective {
  @Input() disabled: boolean;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant