[英]How to update ngModel from directive?
我創建了一個指令來限制input
字段type=number
的長度。
//輸入
<input min="1" appLimitTo [limit]="5" type="number" name="property" [(ngModel)]="property">
//指令
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();
}
}
}
如果我們通過鍵盤輸入值,則效果很好。 但是,如果我復制並粘貼此數字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();
}
}
用法:
<input ngModel appLimitTo="3" type="number" />
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.