【问题标题】:Applying a pipe or transform to a Reactive Form value将管道或转换应用于反应式表单值
【发布时间】:2017-03-30 23:10:18
【问题描述】:

我正在构建一个简单的响应式表单。为简单起见,假设我要显示的唯一数据是日期。

test.component.html

<form novalidate [formGroup]="myForm">
       <input type="date" formControlName="date">
</form>

test.component.ts

private date: Date = Date.now();
ngOnInit() {
        this.myForm = this.fb.group({
            date: [this.date, [Validators.required]]
        });
    }

模板上的输入类型=日期字段要求日期格式为“yyyy-MM-dd”。 event 中的值是一个 JavaScript Date 对象。

如何在模板级别修改数据,使输入值正确?


我的尝试:

执行此操作的一种方法是将 DatePipe 注入我的组件并在代码中应用转换。

date: [datePipe.transform(this.event.date, 'yyyy-MM-dd'), [Validators.required]]

但这会将模板的实现细节与组件联系起来。例如,如果 NativeScript 模板要求日期格式为MM/dd/yyyy,该怎么办? formGroup 不再有效。

【问题讨论】:

  • 对不起,但我认为这是唯一的方法......我个人会使用服务来检索日期格式(通过MyModule.forRoot("myFormat") 动态设置),因此您可以在多个平台上使用它。

标签: date angular angular-pipe


【解决方案1】:

在@n00dl3 的帮助下,我能想到的唯一方法是包装 md-input 组件并通过 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) : '');
        }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-10-04
    • 2017-07-29
    • 1970-01-01
    • 1970-01-01
    • 2018-09-06
    • 2016-08-09
    • 2021-11-08
    • 1970-01-01
    相关资源
    最近更新 更多