Angular 2刷新视图上的ngModel

时间:2016-11-04 13:07:59

标签: angular angular2-template

我有下一个时间输入组件

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

一切正常,除非我有10:30并且我想写10:303 重新绑定ngModel值导致这不会通过过滤器,并在 ngModel我有最后一个有效的值。 任何人都知道如何实现这一目标?

0 个答案:

没有答案