Trying to submit a form on a model in Ionic v4

Issue

I’m building a web application with Ionic and Angular, in this page I have the data from an animal, but I also need to add the vaccines that the animal has taken.

I’m using a modal on the save page of the animal. The data in the Save Page can be submited without the vaccines, and is working, but I have a problem trying to submit the vaccines form in the modal.

This is the method that opens the modal in the SavePage:

async saveVacinas(){
    const modal  await this.modalCtrl.create({
      component: VacinasPage
      });

      await modal.present();


    }

This is the code in the VaccinesPage

export class VacinasPage implements OnInit {
  vacinaForm: FormGroup;

  constructor(private modelCtrl: ModalController, private fb: FormBuilder, private vacinaService: VacinaService) { }

  ngOnInit(): void {
    this.createForm();
  }

  private createForm(): void{
    this.vacinaForm  this.fb.group({
      nome: ['',[Validators.required]]
    });
  }

  onSubmit(): void{
      console.log(this.vacinaForm.value);
  }

}

HTML:

<ion-header>
  <ion-toolbar>
    <ion-title>vacinas</ion-title>
  </ion-toolbar>
</ion-header>

<ion-content>
  <form [formGroup]"vacinaForm" (submit)"onSubmit()">
    <ion-item>
      <ion-label>Teste</ion-label>
      <ion-input
        type"text"
        placeholder"Awesome Input"
        formControlName"nome"
      ></ion-input>
    </ion-item>

    <ion-button type"submit">Click me</ion-button>
  </form>
</ion-content>

And when I submit the form, the SavePage refresh, and it can’t find the animal’s ID in the database.

Solution

If you’re trying to pass back the data from the modal to the parent you can do something like this:

So in the parent comp (your SavePage)

async saveVacinas(){
    const modal  await this.modalCtrl.create({
      component: VacinasPage
      });

      await modal.present();

      modal.onDidDismiss().then((data) > {
      // do something with the data ... 
      console.log(data);
    });
}

and in your VaccinesPage where you submit, pass the data to the dismiss method:

export class VacinasPage implements OnInit {
  vacinaForm: FormGroup;

  constructor(private modalController: ModalController, private fb: FormBuilder, private vacinaService: VacinaService) { }

  ngOnInit(): void {
    this.createForm();
  }

  private createForm(): void{
    this.vacinaForm  this.fb.group({
      nome: ['',[Validators.required]]
    });
  }

  onSubmit(): void{
      console.log(this.vacinaForm.value);
      this.modalController.dismiss(this.vacinaForm.value);
  }
}

Answered By – Andrei Fara

Leave a Comment