如何从指令更新 ngModel?

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事件。

limit-to.directive.ts

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

Live demo