繁体   English   中英

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

[英]Angular Directive selector by variable attribute value

是否可以根据变量属性值创建自定义指令? 是这样的:

@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
}

然后在组件 HTML

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

它工作正常,第一个输入将由 NumericDirective 处理,第二个将由 XXXDirective 处理。

我可以这样实现我的目标

<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>

我的问题是有什么方法可以将此开关简写为类似于以下行的内容,而 angular 可以执行相同的行为吗?

<input [inputmode]="currentMode" />

当我这样做时:没有任何指令将应用于输入。 通过在 ts 代码中设置 currentMode 值,似乎 Angular 不支持通过动态选择器属性值构建指令。 我认为它最初通过 selector 属性值创建一个指令,因为它尚未设置,所以它没有检测到正确的指令并忽略它。

实现此目的的任何解决方案或解决方法。 主要目的是在运行时设置 currentMode 并期望应用正确的指令行为。

好的,我已经设法让它工作了。

首先,您必须将指令选择器设置为“input:[inputMode]”。 然后你必须创建一个名为 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