ionic 2:在页面内的 FORM 中添加自定义输入组件/最终目标:在 Ionic 2 Form 中集成 "cordova-plugin-datepicker"

ionic 2: add custom input component in a FORM within a page / Final goal: integrate "cordova-plugin-datepicker" in Ionic 2 Form

在 ionic 2 版本中:

使用 Ionic 2 FORM,输入:<ion-datetime> 恰好很慢 (see here).

我想绕过它并改用 "cordova-plugin-datepicker"。我有很多问题要让它发挥作用。但我将从这里开始我需要实现的第一步:实现可用作 <ion-[something for a form input]> 标记的自定义选择器。

首先,我们将尝试通过另一个组件.

实现标签 <ion-datetime>

我发现了类似的问题 . It tells to import:import {IONIC_DIRECTIVES} from 'ionic-angular'; and to add in the @Component annotation the metadata: directives: [IONIC_DIRECTIVES]. But in Angular 2 documentation 元数据 directives 已不存在。如果我尝试这样做,我会收到错误消息。

现在我的代码:

我有一个用户表单页面:

import { Component } from '@angular/core';
import { FormBuilder, FormGroup, Validators } from '@angular/forms';
import { NavController, NavParams } from 'ionic-angular';
import { NativeDatePickerTag } from '../../custom-components/native-date-picker/native-date-picker';

@Component({
    selector:'user-form',
    templateUrl: 'user-form.html',
    providers: [Validators]
})
export class UserFormPage {
    private readonly PAGE_TAG:string = "UserFormPage";
    public birthdate:any;
    public userForm:FormGroup;

    constructor(public navCtrl: NavController, public navParams: NavParams, public fb:FormBuilder, public validators:Validators){}

    public updateUserData = () => {
        console.log(this.userForm.value);
    }

    ionViewDidLoad(){
        console.log(this.PAGE_TAG + " ionViewDidLoad() starts");
        this.userForm = this.fb.group({
            birthday: [this.birthdate,Validators.required],
        });
    }
}

在我的 'user-form.html' 中它看起来像这样:

           <ion-content>
            <form (ngSubmit)="updateUserData()" [formGroup] = "userForm" >
               <ion-item>
                <ion-label stacked>Birthdate</ion-label>
                <native-date-picker [controlName]="birthday"></native-date-picker>
              </ion-item>
              <button ion-button type="submit"  block>Submit</button>
            </form>
        </ion-content>

还有我的自定义组件 NativeDatePickerTag(同样,这是一个尚未实现 cordova-plugin-datepicker 的概念证明):

import { Component, Input, ViewChild, ElementRef } from '@angular/core';
import { Platform } from 'ionic-angular';
import { FormGroup, FormControl } from '@angular/forms';

@Component({
    selector: 'native-date-picker',
    template: `
    <ion-datetime  [formControlName]='this._controlName'></ion-datetime>
    `
})
export class NativeDatePickerTag {
    private readonly COMPONENT_TAG = "NativeDatePickerObj";
    public _controlName: FormControl;

    @Input () set controlName(newControl: FormControl){
        this._controlName = newControl;
    }


    constructor(public platform:Platform){
    }

}

如果我 运行 这样的代码,它会在 console.log:

formControlName must be used with a parent formGroup directive

我不明白为什么它不考虑 formGroup 选择器 native-date-picker 嵌入在 'user-form.html' 中。所以我试图从 'customer-form.html' 传递 formGroup 来纠正这个错误。

在'user-form.html'我已经改变了, <native-date-picker [controlName]="birthday"></native-date-picker> 和: <native-date-picker [groupName]="userForm" [controlName]="birthday"></native-date-picker>

并且在 NativeDatePickerTag 中,我将注释更改为:

@Component({
    selector: 'native-date-picker',
    template: `<div [formGroup]='this._formGroup'>
    <ion-datetime  [formControlName]='this._controlName'></ion-datetime>
    </div>
    `
})

我在 class NativeDatePickerTag 中添加了以下内容: public_formGroup:表单组;

    @Input () set groupName(newGroup: FormGroup){
        this._formGroup = newGroup;
    }

现在我进入 console.log:

Cannot find control with unspecified name attribute

我真的不明白我做错了什么。任何有这方面经验的人都可以给我一些指导吗?

我找到了解决方案,关键是要了解工作原理ControlValueAccessor interface

我通过通读 link:

这里要求的是代码:

本机日期-picker.ts:

import { Component, Input, Output, ViewChild, ElementRef, forwardRef, EventEmitter } from '@angular/core';
import { FormGroup, FormControl, NG_VALUE_ACCESSOR, NG_VALIDATORS, ControlValueAccessor } from '@angular/forms';

import { FormValidators } from '../../form-validators/form-validators';

import { Platform } from 'ionic-angular';
import { DatePicker } from 'ionic-native';
import { TranslationService } from '../../services/translation/translation';


import moment from 'moment/min/moment-with-locales.min.js';

export const CUSTOM_INPUT_CONTROL_VALUE_ACCESSOR: any = {
    provide: NG_VALUE_ACCESSOR,
    useExisting: forwardRef(() => NativeDatePickerTag),
    multi: true
};

declare var datePicker: any;


@Component({
    selector: 'native-date-picker',
    templateUrl: 'native-date-picker.html',
    providers:[CUSTOM_INPUT_CONTROL_VALUE_ACCESSOR]

})
export class NativeDatePickerTag implements ControlValueAccessor {

    private readonly COMPONENT_TAG = "NativeDatePickerTag";

    //The internal data model
    public dateValue: any = '';

    public pickerType=null;
    public _labelForNDP:any;
    public displayFormatForIonDateTime:string;
    public ionDateTimeMonthsShort:string;
    public ionDateTimeMonthsLong:string;

    @Input() submitAttempt;
    @Input() control;
    @Input () set labelForNDP(value:any){
      this._labelForNDP = value;
      console.log("labelForNDP : " + value);
    }
    @Output () onChange: EventEmitter<any> = new EventEmitter();

     //Set touched on ionChange
     onTouched(){
            console.log(this.COMPONENT_TAG + " onTouched() starts");
            this.control._touched=true;
     }

    //From ControlValueAccessor interface
    writeValue(value: any) {
        console.log(this.COMPONENT_TAG + " writeValue("+value+") starts");
        if (value !== undefined || value !== null) {
            this.dateValue = (new moment(value)).format('YYYY-MM-DD');
        }
        console.log(this.COMPONENT_TAG + " writeValue("+value+") this.dateValue " + this.dateValue);

    }

    diplayDateAccordingToSettings(date:any){ 
      console.log(this.COMPONENT_TAG + " diplayDateAccordingToSettings("+date+")");
      let dateToBeDisplayed:any;
      if(moment(date,'YYYY-MM-DD').isValid()){
        dateToBeDisplayed = (new moment(date)).locale(this.trans.getCurrentLang()).format(this.displayFormatForIonDateTime);
      console.log(this.COMPONENT_TAG + " diplayDateAccordingToSettings("+date+")" + " GIVES " + dateToBeDisplayed);
      } else {
        dateToBeDisplayed="";
      }
      return dateToBeDisplayed;
    }

    updateDate(event:any) {       
        console.log(this.COMPONENT_TAG + " updateDate() starts");
        console.info(event);
        let newValue = "I'm new value";
        let dateToSetOn = (new moment(event)).format('YYYY-MM-DD');
        console.log(this.COMPONENT_TAG + " updateDate() about to return " + dateToSetOn);
        this.onTouched();
        this.onChange.next(dateToSetOn);
    }


    //From ControlValueAccessor interface
    registerOnChange(fn: any) {
        console.log(this.COMPONENT_TAG + " registerOnChange() starts");
        console.info(fn);
        this.onChange.subscribe(fn);
    }

    //From ControlValueAccessor interface
    registerOnTouched(fn: any) { //leave it empty
    }


    // get the element with the # on it
    @ViewChild("nativeDatePicker") nativeDatePicker: ElementRef; 
    @ViewChild("ionDatePicker") ionDatePicker: ElementRef; 

    constructor(public platform:Platform, public trans:TranslationService){
      console.log(this.COMPONENT_TAG + " constructor() starts");
      console.info(this);
      this.displayFormatForIonDateTime = moment.localeData(this.trans.getCurrentLang())._longDateFormat['LL'];
      this.ionDateTimeMonthsShort =  moment.localeData(this.trans.getCurrentLang()).monthsShort();
      this.ionDateTimeMonthsLong =  moment.localeData(this.trans.getCurrentLang()).months();

      this.setFieldWhenPlatformReady();
    }

    private setFieldWhenPlatformReady = () => {
      this.platform.ready().then(() => {
        if(this.platform.is('android')){
          this.pickerType = "android";
        } else if (this.platform.is('ios')) {
          // ios case: NOT DONE YET
        } else if (this.platform.is('core')) {
          this.pickerType = "core";
        }
       }
      );
    }

    public dateInputManagement = () => { 
          console.log(this.COMPONENT_TAG + " dateInputManagement() starts");
          let dateToUseOnOpening = (moment(this.dateValue,'YYYY-MM-DD').isValid())?new Date(moment(this.dateValue,'YYYY-MM-DD')):new Date();

          console.info(dateToUseOnOpening);

          let options = {
              date: dateToUseOnOpening,
              mode: 'date',
              androidTheme: datePicker.ANDROID_THEMES.THEME_HOLO_LIGHT
          };

          DatePicker.show(options).then(
              (date) => {
              let lang = this.trans.getCurrentLang();

               this.writeValue(new moment(date));
               this.updateDate(new moment(date));
          }).catch( (error) => { // Android only
          });
    }

}

和本机日期-picker.html:

<ion-item>
    <ion-label stacked>{{_labelForNDP}}</ion-label>

    <ion-datetime #ionDatePicker [displayFormat]="displayFormatForIonDateTime" [monthShortNames]="ionDateTimeMonthsShort" [monthNames]="ionDateTimeMonthsLong" *ngIf="pickerType=='core' || pickerType=='ios'" name="birthday" [ngModel]="dateValue" (ngModelChange)="updateDate($event)" [class.invalid]="!control.valid && (control.touched||submitAttempt)"></ion-datetime>

    <ion-input #nativeDatePicker type="text" disabled=true (click)="dateInputManagement()" *ngIf="pickerType=='android'" name="birthday" [ngModel]="diplayDateAccordingToSettings(dateValue)"  (ngModelChange)="updateDate($event)" [class.invalid]="!control.valid && (control.touched||submitAttempt)"></ion-input>

</ion-item>

并且在包含调用它的表单的组件的 HTML 模板中,尊重需要提供给 class NativeDatePicker 的 @input,它必须看起来像那:

  <native-date-picker [labelForNDP]="LABEL" #nativeDatePickerOnUserPage formControlName="date" [control]="userForm.controls['date']" [submitAttempt]=submitAttempt>
  </native-date-picker>