角度指令多个选择器和@ HostListener,@ HostBinding

时间:2018-10-24 08:42:52

标签: angular

本文介绍了如何在同一个单一指令中实现多个选择器:

https://www.bennadel.com/blog/3367-matching-multiple-selectors-on-the-same-element-creates-a-single-directive-instance-in-angular-5-0-0.htm

@Directive({
    selector: "[everySecond] , [everyTwoSeconds]",
    outputs: [
        "everySecond",
        "everyTwoSeconds"
    ]
})
export class PingDirective implements OnInit, OnDestroy {
   @HostListener('mouseleave') mouseleave(e:Event){}
   @HostBinding('background-color') backgroundColor: string;
}

但是当我定义@HostListener@HostBinding时,两者都是相同的指令PingDirective

可以单独定义吗?对于以下结构,您可以侦听不同的span事件并定义css everySecondeveryTwoSeconds

<span everySecond> 
 everySecond 
 <span everyTwoSeconds>
 everyTwoSeconds
 </span>
</span>

2 个答案:

答案 0 :(得分:1)

是的,可以。只需为指令的每个选择器定义一个@Input属性:

export class PingDirective {
   @Input() everySecond: boolean;
   @Input() everyTwoSeconds: boolean;

   ngOnInit() {
     if (this.everySecond) console.log('every second!');
   }
}

之所以可行,是因为Angular允许您为指令定义Input properties。输入属性的名称也可以与选择器相同(通过这种方式,您可以将数据传递给指令,例如,[timeout]="1"用于带有selector: '[timeout]'的指令)。

使用上面的代码,您对Angular说您希望指令使用两个Input,它们可以都存在(并且两个变量都为true),只能存在一个,但是至少应存在一个,否则@Directive选择器将不匹配

答案 1 :(得分:1)

也许您可以定义另一个输入,即atype ='events'或atype ='css'。

基于输入类型,您可以处理单击事件并定义CSS属性。

<span everySecond="true" atype="events"> 
 everySecond 
 <span everyTwoSeconds atype="css">
 everyTwoSeconds
 </span>
</span>

https://stackblitz.com/edit/angular-nwobuk