【问题标题】:Angular4: input not updated correctly after model.valueAccessor.writeValue( value )Angular4:在 model.valueAccessor.writeValue( value ) 之后输入未正确更新
【发布时间】:2018-12-05 04:41:11
【问题描述】:

我有两个输入连接到同一型号。使用 model.valueAccessor.writeValue( value ) 通过指令将值合二为一不会正确更新。似乎是前一个值。

HTML 视图 - 简化(不知道为什么它没有突出显示语法):

<tr *ngFor="let intvObj of intervals; let $index = index">
 <td><input [appPdMask]="'time'" [(ngModel)]="intervals[ $index - 1 ].from" name="{{ 'from' + $index }}" type="text"></td>
 <td><input [appPdMask]="'time'" [(ngModel)]="intvObj.to" name="{{ 'to' + $index }}" type="text"></td>
</tr>

输入掩码指令 - ts:

  import { Directive, HostListener, Input } from '@angular/core';
  import { NgControl } from '@angular/forms';

  @Directive({
    selector: '[appPdMask][ngModel]'
  })
  export class PdInputMaskDirective {

    @Input() appPdMask = 'time';

    constructor (
      public model: NgControl
    ) {}

    @HostListener('ngModelChange', ['$event'])
    onInputChange( value ) {
      switch ( this.appPdMask ) {
        case 'time':
          const x = value.replace(/\D/g, '').match(/(\d{0,2})(\d{0,2})/);
          value = !x[2] ? x[1] : x[1] + ':' + x[2];
          break;

        default:
          // do nothing
          break;
      }
      this.model.valueAccessor.writeValue(value);
    }
  }

由于我还没有找到如何在 SO 代码片段中重现 angular4 应用程序的方法,因此这里是 stackblitz 上的重现: https://stackblitz.com/edit/angular-fwrzaj?file=src%2Fapp%2Fapp.component.html

【问题讨论】:

    标签: angular


    【解决方案1】:

    我的同事带来了指令修复: https://stackblitz.com/edit/angular-jrf1jn

    import { Directive, HostListener, Input, OnInit, OnDestroy } from '@angular/core';
    import { NgModel } from '@angular/forms';
    import { Subject, pipe } from 'rxjs';
    import { takeUntil } from 'rxjs/operators';
    
    @Directive({
      selector: '[appPdMask][ngModel]'
    })
    export class PdInputMaskDirective implements OnInit, OnDestroy {
    
      @Input() appPdMask = 'time';
    
      constructor (
        public model: NgModel,
      ) {}
    
      private _unsubscribeAll = new Subject<void>();
    
      ngOnInit() {
        this.model.valueChanges
          .pipe(
            takeUntil(this._unsubscribeAll)
          )
          .subscribe(val => {
            const newVal = this._parseValue(val);
            this.model.valueAccessor.writeValue(newVal);
          });
      }
    
      ngOnDestroy() {
        this._unsubscribeAll.next();
        this._unsubscribeAll.complete();
      }
    
      private _parseValue( v ) {
        const x = v.replace(/\D/g, '').match(/(\d{0,2})(\d{0,2})/);
        return !x[2] ? x[1] : x[1] + ':' + x[2];
      }
    }
    

    现在它可以按预期工作了 :) 非常感谢 @seyd :clap:

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2022-01-19
      • 1970-01-01
      • 1970-01-01
      • 2020-08-24
      • 1970-01-01
      • 2017-03-15
      • 1970-01-01
      相关资源
      最近更新 更多