问题
I have the next component which is a time input
@Component({
selector: 'time-cell',
template: `<input #input [ngModel]="value" (ngModelChange)="onModelChange($event)" placeholder="00:00">`,
encapsulation: ViewEncapsulation.None
})
export class TimeCellEditorComponent implements AgEditorComponent, AfterViewInit {
value: string;
private oldValue: string;
private onValueChangeSubject: Subject<string>;
private timeSplitRegExp: RegExp = /^\s*([01]?\d|2[0-3])(:?([0-5]\d))?\s*$/;
private timeValidationRegExp: RegExp = /^([0-9]|0[0-9]|1[0-9]|2[0-3]):[0-5][0-9]$/;
@ViewChild('input', { read: ViewContainerRef }) private input;
agInit(params: any): void {
this.params = params;
this.value = this.params.value;
this.onValueChangeSubject = new Subject<string>();
this.onValueChangeSubject
.filter((v) => {
let filterResult = this.isTimeValid(v);
if (!filterResult) {
this.value = this.value.substr(0, this.value.length);
}
return filterResult;
})
.debounce(() => { return Observable.timer(400); })
.map<string>(this.formatTime.bind(this))
.distinctUntilChanged()
.subscribe(v => {
this.value = v;
});
}
getValue(): any {
return this.value;
}
onModelChange($event) {
this.onValueChangeSubject.next($event);
}
isTimeValid($event): boolean {
$event = $event || "";
if ($event.length > 5) {
return false;
}
let formatedTime = this.formatTime($event);
return this.timeValidationRegExp.test(formatedTime);
}
ngAfterViewInit() {
this.input.element.nativeElement.focus();
}
private getCharCodeFromEvent(event): any {
event = event || window.event;
return (typeof event.which === "undefined") ? event.keyCode : event.which;
}
private formatTime(time: string): string {
let result = "00:00";
time = time.substr(0, 5);
let regexResult = time.match(this.timeSplitRegExp);
if (regexResult) {
result = (regexResult[1].length === 2 ? "" : "0") + regexResult[1] + ":" + (regexResult[2] || "00");
}
return result;
}
Everything works fine except that if I have 10:30
and I write 10:303
I want to
rebind the ngModel
value cause this will not pass the filter, and in the
ngModel
I have the last value which was valid.
Anyone have any idea how can I achieve this ?
来源:https://stackoverflow.com/questions/40423484/angular-2-refresh-ngmodel-on-the-view