Applying a pipe or transform to a Reactive Form value

血红的双手。 提交于 2019-11-30 14:55:16

The only way I've been able come up, with the help of @n00dl3 is to wrap the md-input component and provide the proper value via a ControlValueAccessor

    import { Component, Input, ViewChild } from '@angular/core';
    import { ControlValueAccessor, NG_VALUE_ACCESSOR } from '@angular/forms';
    import { DatePipe } from '@angular/common';
    import { MdInput } from '@angular/material';

    @Component({
        selector: 'md-date-input',
        template: `
        <md-input [placeholder]="placeholder"
            type="date"
            (change)="update()"
            [value]="dateInput">
        </md-input>`,
        providers: [
            { provide: NG_VALUE_ACCESSOR, useExisting: DateInputComponent, multi: true }]
    })
    export class DateInputComponent implements ControlValueAccessor {
        @Input() placeholder: string;
        @ViewChild(MdInput) mdInput: MdInput;

        dateInput: string;

        onChange: (value: any) => void;

        constructor(private datePipe: DatePipe) {
        }

        writeValue(value: any) {
            this.dateInput = value == null ? '' : this.datePipe.transform(value, 'yyyy-MM-dd');
        }

        registerOnChange(fn: (value: any) => void) {
            this.onChange = fn;
        }

        registerOnTouched(fn: (value: any) => void) {
        }

        update() {
            this.onChange(this.mdInput.value ? new Date(this.mdInput.value) : '');
        }
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!