自定义angular中的Directive

背景:

我们在一些组件或者component使用时想实现一些动态显示效果,比如鼠标移动上去或者一些其他事件,使用directive就可以很清晰的实现我们想要的效果。

1.创建一个指令

使用ng g directive xxx构建一个directive指令,该指令在app下,我们也可以创建一个文件夹把我们的directive.ts放在里面。不过别忘了导入我们的指令class

@NgModule({

  declarations: [

    AppComponent,

    xxxDirective

  ],

2.指令的逻辑代码:

import { Directive, HostBinding, HostListener, Input, ElementRef } from '@angular/core';
import { NgForm } from '@angular/forms';


@Directive({
    // 使用CSS选择器,如果属性中有appHbBackground,就表示使用了该主键
    selector: '[inputTest]'
})
export class RainbowDirective {
    // 使用依赖注入的方式,el 代表使用指令的控件
    constructor(private el: ElementRef) {
        this.el = el;
    }
    // 接收属性 appHbBackground的值,并且将值传递给bgColor变量
    @Input('inputTest') dataColor: NgForm;

    // 给使用指令的控件添加 mouseenter的事件
    @HostListener('input') onMouseEnter() {
        console.log(this.dataColor)
        //通过this.el.nativeElement找到宿主元素,再去设置属性
        if (this.dataColor) {
            this.el.nativeElement.style.border = '1px solid red'
            this.el.nativeElement.style.color = '1px solid red !important'
        }
        else {
            this.el.nativeElement.style.border = '1px solid  #ccc'
            this.el.nativeElement.style.color = '1px solid  #ccc'
        }
    }
    @HostBinding('style.border') borderColor: string;//通过@HostBinding去设置样式
    @HostBinding('style.color') textColor: string;//通过@HostBinding去设置样式
}

以上我们通过两种方式可以实现去宿主元素样式的修改。

3.绑定要html

<div> <p [inputTest]=false>subpage works!</p> </div>

参考angular官网的链接:angular-drective.cn

扫描二维码关注公众号,回复: 11353398 查看本文章

猜你喜欢

转载自blog.csdn.net/qq_40677590/article/details/103261374