Yas*_*nik 3 input dom-events angular2-directives angular
我创建了一个指令来限制input字段的长度type=number。
//输入
<input min="1" appLimitTo [limit]="5" type="number" name="property" [(ngModel)]="property">
Run Code Online (Sandbox Code Playgroud)
//指令
import {Directive, HostListener, Input} from '@angular/core';
@Directive({
selector: '[appLimitTo]',
})
export class LimitToDirective {
@Input() limit: number;
@Input() ngModel: any;
@HostListener('input', ['$event'])
onInput(e) {
if (e.target.value.length >= +this.limit) {
e.target.value = (e.target.value).toString().slice(0, this.limit - 1);
e.preventDefault();
}
}
}
Run Code Online (Sandbox Code Playgroud)
如果我们通过键盘输入值,则效果很好。但是,如果我复制并粘贴12345678913465789此数字,则会出现问题,该行将其e.target.value = (e.target.value).toString().slice(0, this.limit - 1);缩短到极限,但ngModel仍然包含12345678913465789值。如何更新此ngModel值?
请帮忙。
PS-我应该在指令中添加些什么以满足要求?
您可以注入NgControl自己的指令。然后,您可以收听控制valueChanges事件。
限制指令
import {Directive, HostListener, Input, OnInit, OnDestroy} from '@angular/core';
import {NgControl} from '@angular/forms';
import {map} from 'rxjs/operators';
import {Subscription} from 'rxjs/Subscription';
@Directive({
selector: '[appLimitTo]',
})
export class LimitToDirective implements OnInit, OnDestroy {
@Input('appLimitTo') limit: number;
private subscription: Subscription;
constructor(private ngControl: NgControl) {}
ngOnInit() {
const ctrl = this.ngControl.control;
this.subscription = ctrl.valueChanges
.pipe(map(v => (v || '').toString().slice(0, this.limit)))
.subscribe(v => ctrl.setValue(v, { emitEvent: false }));
}
ngOnDestroy() {
this.subscription.unsubscribe();
}
}
Run Code Online (Sandbox Code Playgroud)
用法:
<input ngModel appLimitTo="3" type="number" />
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1194 次 |
| 最近记录: |