简体   繁体   English

Angular 按变量属性值的指令选择器

[英]Angular Directive selector by variable attribute value

is it possible to create a custom directive based on a variable attribute value?是否可以根据变量属性值创建自定义指令? something like that:是这样的:

@Directive({
    selector: 'input:[inputmode=numeric], input:[inputmode=decimal]',
})
export class NumericDirective{
// Dom manipulation and huge implementation to let that input accept only numbers and handle spin up and down and format the display value on blur and parse value on focus ..... etc.
}

@Directive({
    selector: 'input:[inputmode=XXX]',
})
export class XXXDirective{
// a total implementation and constructor DI to achieve different job
}

and then in component HTML然后在组件 HTML

<input inputmode="decimal" />
<input inputmode="XXX" />

it works fine, the first input will be handled by NumericDirective and the second will be handled by XXXDirective.它工作正常,第一个输入将由 NumericDirective 处理,第二个将由 XXXDirective 处理。

I can achieve my goal like this我可以这样实现我的目标

<ng-container [ngSwitch] ="currentMode">
<input *ngSwitchCase="numeric" inputmode="numeric" /> // apply different directive based on selector = input[numeric]
<input *ngSwitchCase="decimal" inputmode="decimal" /> // apply different directive based on selector = input[decimal]
<input *ngSwitchCase="XXX" inputmode="XXX" /> // apply different directive based on selector is input[XXX]
....
</ng-container>

my question is there is any way to shorthand this switch to be something like the following line and angular can do the same behavior?我的问题是有什么方法可以将此开关简写为类似于以下行的内容,而 angular 可以执行相同的行为吗?

<input [inputmode]="currentMode" />

when I do that: None of the directives will be applied to the input.当我这样做时:没有任何指令将应用于输入。 by setting currentMode value in ts code it seems that Angular did not support build directive by dynamic selector attribute value.通过在 ts 代码中设置 currentMode 值,似乎 Angular 不支持通过动态选择器属性值构建指令。 I think it creates a directive initially by selector attribute value and since it is not set yet it did not detect the proper directive and just ignore it.我认为它最初通过 selector 属性值创建一个指令,因为它尚未设置,所以它没有检测到正确的指令并忽略它。

any solution or workaround to achieve this.实现此目的的任何解决方案或解决方法。 the main purpose is to set currentMode at runtime and expects to apply the proper directive behaviors.主要目的是在运行时设置 currentMode 并期望应用正确的指令行为。

Ok i have managed to get this working.好的,我已经设法让它工作了。

First you have to set your directive selector to 'input:[inputMode]'.首先,您必须将指令选择器设置为“input:[inputMode]”。 Then you have to create an @Input() named inputMode which will listen for the injected value.然后你必须创建一个名为 inputMode 的 @Input() 来监听注入的值。

@Directive({
  selector: 'input:[inputMode]'
})
export class NumericDirective implements AfterViewInit{

  @Input() inputMode?: string;

  constructor(private elRef: ElementRef<HTMLInputElement>) {}

  ngAfterViewInit(): void { alert(this.inputMode); }

}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM