Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to validate ion-datetime tag in Ionic 4 app?

Tags:

I'm building Ionic 4 app with Angular 7. Why required doesn't work in ion-datetime tag? Below is my code:

<ion-item>
        <ion-label>In Time</ion-label>
        <ion-datetime displayFormat="HH:mm" [(ngModel)]="todo.myInTime" required></ion-datetime>
    </ion-item>
    <ion-item>
        <ion-label>Out Time</ion-label>
        <ion-datetime displayFormat="HH:mm" [(ngModel)]="todo.myOutTime" required></ion-datetime>
    </ion-item>
 <ion-button expand="full" (click)="saveTodo()">Save</ion-button>

Update

I am adding my Component.ts file.

async saveTodo(){
    const loading = await this.loadingController.create({
      message: 'Saving.. Please Wait!'
    });

    await loading.present();

    if(this.todoId)
    {
      this.todoService.updateTodo(this.todo, this.todoId).then(() => {
        loading.dismiss();
        this.nav.goBack();
      })

    }else{
      this.todoService.addTodo(this.todo).then(() => {
        loading.dismiss();
        // this.nav.navigateBack('home');
        this.router.navigate(['/home']);
      })
    }
  }
like image 640
Abhijit Mondal Abhi Avatar asked Jan 30 '19 04:01

Abhijit Mondal Abhi


1 Answers

You need to use angular form controls to show validations. You can do it as below.

HTML

<form [formGroup]="myGroup">
  <ion-item>
    <ion-label>Start Time</ion-label>
    <ion-datetime formControlName="datetime" [(ngModel)]="fData. datetime" displayFormat="HH:mm"></ion-datetime>
  </ion-item>
</form>

TS

export class ExamplePage {

  myGroup: FormGroup;
  fData = { "datetime": "" };

  constructor() {

    this.myGroup = new FormGroup({
      datetime: new FormControl('', [Validators.required]),
    });
  }
}

Hope this will helpful and see my stackblitz demo

like image 120
Sudarshana Dayananda Avatar answered Nov 01 '22 16:11

Sudarshana Dayananda