代码之家  ›  专栏  ›  技术社区  ›  Luckylooke

angular4:在model.valueaccessor.writevalue(value)之后输入未正确更新

  •  1
  • Luckylooke  · 技术社区  · 6 年前

    我有两个输入连接到同一个模型。在model.valueaccessor.writevalue(value)的VIA指令中更改值时,无法正确更新。似乎是前车之鉴。

    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);
        }
      }
    

    由于我还没有找到如何在如此短的代码中复制Angular4应用程序的方法,下面是StackBlitz上的复制: https://stackblitz.com/edit/angular-fwrzaj?file=src%2Fapp%2Fapp.component.html

    1 回复  |  直到 6 年前
        1
  •  0
  •   Luckylooke    6 年前

    我的同事带着指令来了: 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: