我有一个指令来决定是否必须输入,屏蔽输入等。我遇到了一种情况,我需要向其中添加一个新指令:基本上,这个新指令将掩码功能添加到了输入中。

<input type="text" formInput [rules]="rules"  [(ngModel)]="value" />


这是formInput指令:

export class DefaultFormInputDirective {

@Input() private rules;
private el: ElementRef;

constructor(el: ElementRef) {
    this.el = el;
}

ngOnInit() {
    this.defineRules();
}

defineRules() {

    if(this.rules == undefined) {
        return;
    }

    if(this.rules.indexOf('required') != -1) {
        this.el.nativeElement.required = true;
    }

    if(this.rules.indexOf('numeric') != -1) {
        // Here is where I need to add currencyMask directive
    }

}

}


这是我正在使用的软件包:https://www.npmjs.com/package/ng2-currency-mask

最佳答案

在大多数情况下,我建议将属性直接添加到输入中,因为对我而言似乎更合适。

无论如何,您都可以创建某种输入抽象组件来接受诸如type之类的输入,并与ngModel一起使用(例如,您可以找到有关此herehere的更多信息),并将包含任何内容。输入所需的任何属性和指令。

所以最后看起来可能像这样:

<custom-input type="text" formInput [rules]="rules" [(ngModel)]="value"></custom-input>

然后,您可以隐藏此组件中实际输入必须具有的逻辑:分配所需的属性,指令和许多其他所需的东西。

09-30 18:28
查看更多