将管道或转换应用于“反应形式"值 [英] Applying a pipe or transform to a Reactive Form value

查看:61
本文介绍了将管道或转换应用于“反应形式"值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I'm building a simple reactive form. For simplicity, lets say the only data I want to display is a date.

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]]
        });
    }

模板上的input type = date字段要求日期格式为"yyyy-MM-dd".事件中的值是一个JavaScript Date对象.

The input type=date field on the template requires the date to be in the format of 'yyyy-MM-dd'. The value in event is a JavaScript Date object.

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

我尝试过的事情:

一种方法是将DatePipe注入到我的组件中,并在代码中应用转换.

One way to do this would be to inject the DatePipe into my component and apply the conversion in code.

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

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

But this ties the implementation detail of the template to the component. For example, what if a NativeScript template requires the date to be in the format MM/dd/yyyy? The formGroup is no longer valid.

推荐答案

在@ n00dl3的帮助下,我唯一能想到的方法是包装md-input组件并通过<提供适当的值c1>

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) : '');
        }
}

这篇关于将管道或转换应用于“反应形式"值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆