Edupala

Comprehensive Full Stack Development Tutorial: Learn Ionic, Angular, React, React Native, and Node.js with JavaScript

Ionic Passing Data from Child to Parent Page

An Ionic Angular component is the basic build block of an Angular framework. In the Ionic Angular page are components, we have different techniques of Ionic Passing Data from Child to Parent Page. The component is responsible for managing a template and providing it with the data and logic it needs. Components can contain other components. 

  1. @Input() decorator
  2. Using service
  3. Angular route with a parameter
  4. Content projection from Parent to Child: @ContentChild and @ContentChildren decorator

Prerequisites:
To create and run an Ionic project, We need Node js and Ionic CLI already install in our system, if not then check how to install Node js and Ionic in Ubuntu. Ionic CLI allows us to create an Ionic project, generate application and library code, and perform a variety of ongoing development tasks such as testing, bundling, and deployment. To install the Ionic CLI, open a terminal, and run the following command:

npm install -g @ionic/cli

Methods of Ionic Passing Data from Child to Parent

We have learned, that there are different approaches to passing data from child to parent.

Angular @Input() decorator

We can use the angular @Input() decorator, to send data from parent to child as data flow downwards from higher-level components to lower-level components. By default, all properties of the component are only accessible inside the components and not from outside of its component. To bind child properties to the parent components we need to be explicit about which properties you want to expose to the parent.

You place the @Input decorator next to the instance variable to which the data will be injected from outside. When you pass data into a component from the outside, you pass that data into the component using input properties.
Please read more information and example of angular @Input decorators in our previous articles.

Ionic Service

Angular service also allows us to share data among related or nonrelated components. Angular contains the concept of service: a class containing methods and properties that can be reused by injecting them across application components, directives, and other services.

IonicService is a class that acts as a central repository, as a central business unit we could say something where you can store, where you can centralize your code based on your application.

Example of service to pass data between components or pages.

In Ionic Angular, the components can communicate with each other in many ways for parent/child-related components we can use input and even binding for sharing data.

With service, we can easily share data among related and nonrelated components. In this example, we are creating a service called userService and by using this service when we change the data on the home page and change data can be displayed on a different page called confirm page.

On the home page, we display user information from the service and add a new user information name and age field to the service user.service.ts. We have a confirmed button and clicking on confirm on the home page will route us to confirm page where we can data of the home page from userService.

Ionic Passing Data from Child to Parent

Create confirm page and user service as
>> ionic generate page confirm
>> ionic generate service services/user
Edit the user.service.ts file and add the get/set method to do additional processing when other pages access or set the variables in this common class.

import { Injectable } from '@angular/core';

@Injectable({ providedIn: 'root' })
export class UserService {
  private _name: string;
  private _age: number;

  get name() {
    return this._name;
  }

  set name(name: string) {
    this._name = name;
  }

  get age() {
    return this._age;
  }

  set age(age: number) {
    this._age = age;
  }
}

Edit in home.page.html template file to add | edit user information.

<ion-header [translucent]="true">
  <ion-toolbar>
    <ion-title>
      Ionic 6 Service
    </ion-title>
  </ion-toolbar>
</ion-header>

<ion-content [fullscreen]="true">
  <div class="ion-padding">
    <ion-card>
      <ion-card-header>
        <ion-card-title>What you are entering</ion-card-title>
      </ion-card-header>

      <ion-card-content>
        <ion-badge color="secondary">Name</ion-badge>{{ user.name }}<br /><br />
        <ion-badge color="tertiary">Age</ion-badge> {{ user.age }}
      </ion-card-content>
    </ion-card>

    <ion-list>
      <ion-item>
        <ion-label position="fixed">Name</ion-label>
        <ion-input type="text" [(ngModel)]="user.name"></ion-input>
      </ion-item>
      <ion-item>
        <ion-label position="fixed">Age</ion-label>
        <ion-input type="number" [(ngModel)]="user.age"></ion-input>
      </ion-item>

      <ion-item class="ion-float-right" lines="none">
        <ion-button color="primary" [routerLink]="'/confirm'">Confirm</ion-button>
      </ion-item>
    </ion-list>
  </div>
</ion-content>

Edit n home.page.ts file where we have to inject userService service on our page so that we can use it.

import { Component, OnInit } from '@angular/core';
import { UserService } from '../user.service';

@Component({
  selector: 'app-home',
  templateUrl: 'home.page.html',
  styleUrls: ['home.page.scss'],
})
export class HomePage implements OnInit {
  user: any;

  constructor(private userService: UserService) { }

  ngOnInit() {
    this.user = this.userService;
  }
}

Edit the confirm.page.html template to display data from the home page.

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

<ion-content>
  <ion-card>
    <ion-card-header>
      <ion-card-title>Please confirm your profile</ion-card-title>
    </ion-card-header>

    <ion-card-content>
      {{ user.name }} is {{ user.age }} years old
    </ion-card-content>
    <ion-item float-right>
      <ion-button color="primary" [routerLink]="'/home'">Ok</ion-button>
    </ion-item>
  </ion-card>
</ion-content>

Edit confirm.page.ts file

import { Component, OnInit } from '@angular/core';
import { UserService } from '../user.service';

@Component({
  selector: 'app-confirm',
  templateUrl: './confirm.page.html',
  styleUrls: ['./confirm.page.scss'],
})
export class ConfirmPage implements OnInit {
  user: any;

  constructor(private  userService: UserService) { }

  ngOnInit() {
    this.user = this.userService;
  }
}

Ionic Angular route with parameter

Angular also allows us to send data to navigating components through the route parameter. There are different approaches we can use in an angular route to send data to the child component /page. Check our previous article on how to pass data using the Ionic route.

Conclusion
In this tutorial, we have completely different ways of passing data from the child to the parent component.

Related posts

Ionic Passing Data from Child to Parent Page

Leave a Reply

Your email address will not be published. Required fields are marked *

Scroll to top