Angular4:在model.valueAccessor.writeValue(value)之后输入未正确更新

时间:2018-06-26 12:43:03

标签: angular

我有两个输入连接到同一型号。通过model.valueAccessor.writeValue(value)指令通过一个更改值不能正确更新。似乎是倒数第一。

enter image description here

视图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

1 个答案:

答案 0 :(得分:0)

我的同事附带了指令修复程序: 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: