【问题标题】:Multiple directive selectors - find which selector was used in template多指令选择器 - 查找模板中使用了哪个选择器
【发布时间】:2020-02-25 09:03:00
【问题描述】:

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

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

类似的东西

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

  }
}

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

【问题讨论】:

  • 请看我的回答here是否适合你。
  • 嗨,不完全是。我绝对可以为代码中的元素静态附加指令,但我不想做dirA="false",而是更清楚dirNotA,因为它只有这个指令的可能值,而dirA=12并不实用感觉。
  • 请看我的回答是否适合你。

标签: angular angular-directive


【解决方案1】:

您可以使用继承。

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
}

【讨论】:

  • 是的,可能是,但我正在寻找 1 个指令的解决方案
【解决方案2】:

您可以使用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

【讨论】:

  • 不幸的是,它对我不起作用。 attributesproperty 为空。对于我提出问题的现实生活场景,这在原则上是行不通的。我想使用dirA 作为结构指令,即*dirA,它没有附加元素
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2015-12-26
  • 2012-06-13
  • 1970-01-01
  • 2019-03-28
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多