如何从指令更新ngModel?

时间:2018-04-09 13:15:56

标签: angular input javascript-events angular2-directives

我创建了一个指令来限制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();
        }
    }
}

如果我们通过键盘输入值,它可以正常工作。但是,如果我复制&amp;粘贴12345678913465789此号码,此行e.target.value = (e.target.value).toString().slice(0, this.limit - 1);会将其缩短到限制,但ngModel仍然包含12345678913465789值。如何更新此ngModel值?

请帮助!!

PS - 我应该在指令中添加什么来满足要求

1 个答案:

答案 0 :(得分:4)

您可以将NgControl注入您自己的指令中。然后,您可以收听控件valueChanges事件。

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