formBuilder控件的setValue()和patchValue()方法在Cordova插件的方法调用中不起作用

时间:2019-10-17 10:54:13

标签: angular ionic-framework angular-material cordova-plugins angular-formbuilder

我创建了一个离子标签应用程序,需要使用cordova-plugin-datepicker并使用Angular Material来显示表单字段。

我正在尝试使用onSuccess()方法将文本输入的值设置为从插件的日历中获取的日期,但是它不会更新输入。如果我将代码放在插件的方法之外,例如将其放在test()函数中并在字段上调用,则单击代码将起作用,并将日期正确地输入到输入字段中。

我的html:

<ion-content >
    <div class="ion-text-center tab1-padding">
        <form [formGroup]="newCat" (ngSubmit)="logForm()">
            <mat-form-field appearance="outline" hintLabel="Max 30 caratteri" class="tab1-name-field">
            <mat-label>Nome*</mat-label>
            <input matInput #input maxlength="30" formControlName="name">
            <mat-hint align="end">{{input.value?.length || 0}}/30</mat-hint>
            <mat-error *ngIf="newCat.controls['name'].invalid">Campo obbligatorio</mat-error>
            </mat-form-field>
            <mat-form-field appearance="outline">
            <mat-label>Data di nascita*</mat-label>      
            <input matInput type="text" (click)="viewCalendarAndSetBirthday()" formControlName="birthday">
            <mat-error *ngIf="newCat.controls['birthday'].invalid">Campo obbligatorio</mat-error>
        </mat-form-field>

        <button ion-button type="submit" [disabled]="newCat.pristine || newCat.invalid" class="btn btn-success">Inserisci</button>
        </form>
    </div>
</ion-content>

我的ts:

import { Component } from '@angular/core';
import { FormControl, Validators, FormGroup, FormBuilder } from '@angular/forms';

declare const datePicker;

@Component({
    selector: 'app-tab1',
    templateUrl: 'tab1.page.html',
    styleUrls: ['tab1.page.scss']
})
export class Tab1Page {

    private newCat: FormGroup;

    constructor(private formBuilder: FormBuilder) {
        this.newCat = this.formBuilder.group({
            name: ['', Validators.compose([Validators.maxLength(30), Validators.required])], birthday: ['', Validators.required]});
    }

    logForm() {
        console.log(this.newCat.value);
    }

    viewCalendarAndSetBirthday() {

        // window.alert('test');  //  is working

        const options = {
            date: new Date(),
            mode: 'date'
        };


        datePicker.show(options, this.onSuccess, this.onError);

    }

    onSuccess(date) {
        window.alert('Selected date: ' + date);//THIS FIRES SO IT ENTERS THE METHOD

        this.newCat.controls.birthday.patchValue(date);
    }

    onError(error) { // Android only
        window.alert('Error: ' + error);
    }

    test() {
        this.newCat.controls.birthday.setValue('ciccio');
        this.newCat.controls.birthday.patchValue('pasticcio');
    }

}

1 个答案:

答案 0 :(得分:0)

您可以使用

  1. this.newCat.controls ['birthday']。setValue('ciccio');
  2. this.newCat.patchValue({Birthday:'ciccio'});
相关问题