【发布时间】: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