多个指令选择器-查找模板中使用了哪个选择器

问题描述 投票:0回答:2

我为我的指令有两个选择器dirAdirNotA。该指令应根据使用的选择器继续进行。有什么方法可以确定在指令中使用了哪个选择器?

我既不希望有多个指令,也不希望带有参数的指令。我希望有一个带有多个选择器的指令,并根据模板中使用的选择器确定操作过程。

这样的东西

@Directive({
  selector: '[dirA], [dirNotA]`
})
class DirectiveA implement OnInit {
  ngOnInit() {
    // here we detected which selector was used
    if (dirASelector) {
      ...
    }

  }
}

任何想法如何在指令本身中获取此信息?

angular angular-directive
2个回答
0
投票

您可以使用继承。

class DirectiveAOrNotA implements OnInit {
// common logic here
}

@Directive({
  selector: '[dirA]`
})
export class DirectiveA extends DirectiveAOrNotA {
// differences here
}

@Directive({
  selector: '[dirNotA]`
})
export class DirectiveNotA extends DirectiveAOrNotA {
// differences here
}


0
投票

您可以使用ElementRef并检查其属性中的选择器。

指令

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

@Directive({
  selector: '[dirA], [dirNotA]'
})
class DirectiveA implement OnInit {
  constructor(private _elRef: ElementRef) { }

  ngOnInit() {
    if ((this._elRef.nativeElement.attributes).hasOwnProperty('dirA')) {
      // selector is 'dirA'
    } else if ((this._elRef.nativeElement.attributes).hasOwnProperty('dirNotA')) {
      // selector is 'dirNotA'
    }
  }
}

工作示例:Stackblitz

© www.soinside.com 2019 - 2024. All rights reserved.