Custom Component MdDatePicker used in reactive Form

后端 未结 1 1488
北海茫月
北海茫月 2021-01-26 02:38

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:



        
相关标签:
1条回答
  • 2021-01-26 03:20

    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);
        }
    }
    
    0 讨论(0)
提交回复
热议问题