角度:指令中的updateValueAndValidity [英] Angular: updateValueAndValidity from directive

查看:78
本文介绍了角度:指令中的updateValueAndValidity的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个指令,如果输入值是整数,则在模糊时附加小数.下面是实现.

I have a directive that appends decimals, if the input value is a whole number, on blur. Below is the implementation.

import { Directive, ElementRef, Input, OnInit, HostListener, forwardRef } from '@angular/core';
import { ControlValueAccessor, NG_VALUE_ACCESSOR } from '@angular/forms';

@Directive({
  selector: '[price]',
  providers: [
    {
      provide: NG_VALUE_ACCESSOR,
      useExisting: forwardRef(() => PriceDirective),
      multi: true
    }
  ]
})
export class PriceDirective implements ControlValueAccessor {

  constructor(private el: ElementRef) { }

  // ControlValueAccessor interface
  private _onChange = (_) => { };
  private _onTouched = () => { };

  @HostListener('blur', ['$event'])
  input(event) {
    !!event.target.value ? $(this.el.nativeElement).val(Number(event.target.value).toFixed(2)) : $(this.el.nativeElement).val(null);

    this._onChange(parseFloat(event.target.value));
    this._onTouched();
  }
  writeValue(value: any): void {
    !!value ? $(this.el.nativeElement).val(Number(value).toFixed(2)) : $(this.el.nativeElement).val(null);
  }

  registerOnChange(fn: (_: any) => void): void { this._onChange = fn; }
  registerOnTouched(fn: any): void { this._onTouched = fn; }

}

一切正常.

但是,由于以编程方式更改值时Angular不会触发验证,因此具有该指令的文本框不会得到验证.

But, since Angular doesn't trigger validation when the value is changed programatically, the textbox that has this directive, is not validated.

在这种情况下,除了将 control 引用作为指令的输入并在其上调用 updateValueAndValidity 或调用 input 或 blur 上> updateValueAndValidity .

How can I enable validation in this case, by other means than passing the control reference as an input to the directive and calling updateValueAndValidity on it, or calling updateValueAndValidity on input or blur.

如果有人建议我从该指令本身触发验证的方法,那就太好了.

It would be great if someone suggests me a way to trigger validation from the directive itself.

推荐答案

我以这种方式解决了同样的问题.这是我的第一种方法.

I solved the same problem in this way. It is my first approach.

  update() {

    // ...

    const el = this.el.nativeElement;
    const reg = new RegExp(this.textMaskConfig.replacement);

    el.value = this.prevStr.replace(reg, this.currentChar);

    // ...

  }

但是它不会触发validate事件.因此,我得到了 NgControl 组件,并使用了 setValue()方法.

But It doesn't fire the validate event. So I get the NgControl component and used setValue() method.

  constructor(private el: ElementRef, private ctrl: NgControl) {   
  }

  @HostListener('keydown', ['$event']) onKeyDownHandler(e) {
    this.ctrl.control.setValue(value);
  }

这篇关于角度:指令中的updateValueAndValidity的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆