Custom Component MdDatePicker used in reactive Form

别来无恙 提交于 2020-01-11 13:15:18

问题


I am trying to create a custom component to be used in a angular formGroup.

Here's is how I want to use this custom component:

<form [formGroup]="form">
    ...
    <app-date-picker  formControlName="dateStart"
                  [isConsultation]="isConsultation"
                  [label]="'Du'"
                  [(ngModel)]="agenda.datDeb">
    </app-date-picker>
    ...
</form>

Problem : In the main component (containing this form), The model doesn't get updated when the value changes in my custom component, which is involving a MdDatePicker. Though I am using ControlValueAccessor.

The HTML template of my custome component :

<div class="">
    <span *ngIf="label">{{label}} :</span>
    <md-form-field class="" [ngClass]="isConsultation ? 'no-icon' : 'container-input-date'">
        <input mdInput 
           [mdDatepicker]="pickerDebut" 
           class="consultation"
           [(ngModel)]="theDate">
        <md-datepicker-toggle mdSuffix [for]="pickerDebut"></md-datepicker-toggle>
        <md-datepicker #pickerDebut></md-datepicker>
    </md-form-field>
</div>

And here after you can read the typescript code for my component :

import {Component, Input, ViewChild, forwardRef} from '@angular/core';
import {
  NgModel, 
  ControlValueAccessor, 
  NG_VALUE_ACCESSOR, 
  NG_VALIDATORS,
  FormControl,
} from "@angular/forms";

export function validateDateInputFormat(c: FormControl) {
    // Error content in case input date format is not valid
    let err = {
        formatError: {
            given: c.value,
            acceptedFormat: 'dd/MM/yyyy'
        }
    };

console.log('VALIDATE => c : ', c);

// Control logiq
// return c.value == null ? null : (String(c.value).match(date_regexp)) ? null : err;
return null;
}

@Component({
    selector: 'app-date-picker',
    templateUrl: './date-picker.component.html',
    styleUrls: ['./date-picker.component.scss'],
    providers: [
        {
             provide: NG_VALUE_ACCESSOR,
             useExisting: forwardRef(() => DatePickerComponent),
             multi: true
        },
        {
             provide: NG_VALIDATORS,
             useValue: validateDateInputFormat,
             multi: true
        }
   ]
})
export class DatePickerComponent implements ControlValueAccessor  {

    @Input()
    label : string;
    @Input()
    isConsultation : boolean;

    @ViewChild(NgModel) _theDate: NgModel;

    constructor() { }

    propagateChange = (_: any) => {};
    onTouched: any = () => { };

    writeValue(obj: any): void {
        console.log('writeValue => obj : ', obj);
        if (obj) {
            this._theDate = obj;
        }
    }

    registerOnChange(fn: any): void {
        this.onChange = fn;
        console.log('registerOnChange => fn : ', fn);
    }

    registerOnTouched(fn: any): void {
        this.onTouched = fn;
        console.log('registerOnTouched => fn : ', fn);
    }

    onChange(event){
        console.log('onChange(event) - event => ', event );
        this.propagateChange(event.target.value);
    }

    get theDate() {
        console.log('get theDate()');
        return this._theDate;
    }

    set theDate(val) {
        console.log('set theDate(val) - val => ', val );
        this._theDate = val;
        this.propagateChange(val);
    }
}

What am I doing wrong here ?


回答1:


I managed to overcome this.

Here's the answer.

1st problem :

@ViewChild(NgModel) _theDate: NgModel;

I transformed to

private _theDate : string;

2nd problem : The onChange methode is useless. I removed it and below, the finale TS code for my component:

import {Component, Input, ViewChild, forwardRef} from '@angular/core';
import {
  NgModel, 
  ControlValueAccessor, 
  NG_VALUE_ACCESSOR, 
  NG_VALIDATORS,
  FormControl,
} from "@angular/forms";

export function validateDateInputFormat(c: FormControl) {
    // Error content in case input date format is not valid
    let err = {
        formatError: {
            given: c.value,
            acceptedFormat: 'dd/MM/yyyy'
        }
    };

console.log('VALIDATE => c : ', c);

// Control logiq
// return c.value == null ? null : (String(c.value).match(date_regexp)) ? null : err;
return null;
}

@Component({
    selector: 'app-date-picker',
    templateUrl: './date-picker.component.html',
    styleUrls: ['./date-picker.component.scss'],
    providers: [
        {
             provide: NG_VALUE_ACCESSOR,
             useExisting: forwardRef(() => DatePickerComponent),
             multi: true
        },
        {
             provide: NG_VALIDATORS,
             useValue: validateDateInputFormat,
             multi: true
        }
   ]
})
export class DatePickerComponent implements ControlValueAccessor  {

    @Input()
    label : string;
    @Input()
    isConsultation : boolean;

    private _theDate: string;

    constructor() { }

    propagateChange = (_: any) => {};
    onTouched: any = () => { };

    writeValue(obj: any): void {
        console.log('writeValue => obj : ', obj);
        if (obj) {
            this._theDate = obj;
        }
    }

    registerOnChange(fn: any): void {
        this.propagateChange= fn;
        console.log('registerOnChange => fn : ', fn);
    }

    registerOnTouched(fn: any): void {
        this.onTouched = fn;
        console.log('registerOnTouched => fn : ', fn);
    }

    get theDate() {
        console.log('get theDate()');
        return this._theDate;
    }

    set theDate(val) {
        console.log('set theDate(val) - val => ', val );
        this._theDate = val;
        this.propagateChange(val);
    }
}


来源:https://stackoverflow.com/questions/47885568/custom-component-mddatepicker-used-in-reactive-form

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!