Search code examples
angulartypescriptionic-frameworkionic5angular10

Angular 10/Ionic 5 - Passing input data from a modal to a parent component


I am trying to pass data from an ionic modal with an <ion-input></ion-input>. The data returned is then sent to a firebase backend.

More specifically, I am looking to, on a button press, create a new 'workspace.' This workspace has a title, and when a button is clicked, I want to display a modal asking for a title for this new workspace. On another button press, the title is passed to the parent component, which passes the input data to a new workspace document in firebase. It also gives it an entry of the current users uID.

I am new to angular and ionic, so I am trying 2-way data binding in the modal component, but do not have a firm enough grasp on the ionic/angular mix or the ionic modal to be able to detect the issue.

Currently, this is the error that is being displayed when the modal button is pressed:

Uncaught (in promise): Error: This constructor is not compatible with Angular Dependency Injection because its dependency at index 1 of the parameter list is invalid.
This can happen if the dependency type is a primitive like a string or if an ancestor of this class is missing an Angular decorator.

There is a workspace interface that I have set to any:

export interface Workspace {
  id?: any;
  title?: any;
  description?: any;
  color?: "blue" | "red" | "yellow";
  priority?: any;
}

Here is the parent component .ts with the unnecessary code omitted:

import { Component, OnInit, OnDestroy } from "@angular/core";
import { Workspace } from "../models/workspace.model";
import { Subscription } from "rxjs";
import { WorkspaceService } from "src/app/services/workspace.service";
// ADD THE MODAL
import { ModalController } from "@ionic/angular";
import { WorkspaceModalComponent } from "../modals/workspace-modal.component";

@Component({
  selector: "app-workspaces",
  templateUrl: "./workspaces.component.html",
  styleUrls: ["./workspaces.component.scss"],
})
export class WorkspacesComponent implements OnInit, OnDestroy {
  // HANDLE WORKSPACE SUBSCRIPTION (Some code here not used) 
  workspace: Workspace;
  workspaces: Workspace[];
  sub: Subscription;

  constructor(
    public workspaceService: WorkspaceService,
    public modalController: ModalController
  ) {}

  // GET ALL WORKSPACES AND POPULATE THE WORKSPACES ARRAY
  ngOnInit() {
    this.sub = this.workspaceService
      .getUserWorkspaces()
      .subscribe((workspaces) => {
        this.workspaces = workspaces;
      });
  }

  /**
   * PRESENT THE MODAL FOR CREATING A NEW WORKSPACE
   * RETURN OF AN ASYNC FUNCTION HAS TO BE A PROMISE
   */
  async openWorkspaceModal() {
    const workspaceListModal = await this.modalController.create({
      component: WorkspaceModalComponent,
      // because this is a new workspace, there is no data being passed to the modal component
      componentProps: {},
    });
    workspaceListModal.onDidDismiss().then((data) => {
      if (data) {
        this.workspaceService.createWorkspace({
          title: data,
        });
      }
    });
    return await workspaceListModal.present();
  }
}

Parent html:

<div class="workspaceGrid" style="padding-right: 30px;">
  <!-- [workspace]="workspace" passes the data down to the child component via an input property *ngFor="let workspace of workspaces" -->
  <app-workspace
    *ngFor="let workspace of workspaces"
    [workspace]="workspace"
  ></app-workspace>
  <ion-button (click)="openWorkspaceModal()">
    Open Modal
  </ion-button>
</div>

Here is the custom workspace service .ts helping create the new workspace in the database, with the user ID and the data gathered from the modal (title prop):

import { Injectable } from "@angular/core";
import { AngularFireAuth } from "@angular/fire/auth";
import { AngularFirestore } from "@angular/fire/firestore";
import * as firebase from "firebase/app";
import { switchMap, map } from "rxjs/operators";
import { Workspace } from "../home/models/workspace.model";

@Injectable({
  providedIn: "root",
})
export class WorkspaceService {
  constructor(private afAuth: AngularFireAuth, private db: AngularFirestore) {}

  /**
   *
   * @param data
   * CREATES A WORKSPACE IN THE DATABASE BASED ON THE CURRENTLY LOGGED IN USER
   */
  async createWorkspace(data: Workspace) {
    const user = await this.afAuth.currentUser;
    return this.db.collection("workspaces").add({
      ...data,
      // automatically sets the UID property of the workspace here
      uid: user.uid,
    });
  }
}

The modal component .ts and the modal html:

import { Component, Inject } from "@angular/core";
import { ModalController } from "@ionic/angular";
import { WorkspacesComponent } from "../workspaces/workspaces.component";
import { Workspace } from "../models/workspace.model";

@Component({
  selector: "app-workspace-modal",
  templateUrl: "./workspace-modal.component.html",
  styles: [],
})
export class WorkspaceModalComponent {
  constructor(public modalController: ModalController, public data: any) {}

  /**
   * CLOSE THE MODAL ON CLICK
   */
  async closeWorkspaceModal() {
    await this.modalController.dismiss();
  }
}
<ion-header color="primary" mode="ios">
  <ion-toolbar>
    <ion-title>New Workspace</ion-title>
    <ion-buttons slot="end">
      <ion-button (click)="closeWorkspaceModal()">
        <ion-icon slot="icon-only" name="close"></ion-icon>
      </ion-button>
    </ion-buttons>
  </ion-toolbar>
</ion-header>

<ion-content padding>
  <ion-item>
    <ion-input
      placeholder="Enter a title for the workspace"
      [(ngModel)]="data.title"
    >
    </ion-input>
  </ion-item>
  <!-- HANDLE SUBMISSION OF THE CONTENT -->
  <ion-button [data]="data.title" (click)="closeWorkspaceModal()"
    >Create Workspace</ion-button
  >
</ion-content>

Thank you for any help you could offer!


Solution

  • The problem is in the constructor of WorkspaceModalComponent, you're declaring a variable public data: any. Angular Dependency Injector analyses the type of the variables in the constructor and tries to assign a proper instance according to the type. In this case the type is any so Angular can't figure out what dependency to inject. You should declare this variable as a member of the class instead. Something like this:

    export class WorkspaceModalComponent {
      public data: any;
    
      constructor(public modalController: ModalController) {}
    
      /**
       * CLOSE THE MODAL ON CLICK
       */
      async closeWorkspaceModal() {
        await this.modalController.dismiss();
      }
    }