Transferring information between screens in Ionic Framework 2

I'm a beginner in the world of Ionic and I've encountered an issue with my code. In my restaurant.html page, I have a list of restaurants that, when clicked, should display the full details on another page. However, it seems that the details for each restaurant are not being passed correctly. Can anyone help me figure out where I've gone wrong?

Here is the code:

restaurant.html

<ion-header>

  <ion-navbar color="restaurant-color">
    <button ion-button menuToggle>
      <ion-icon name="menu"></ion-icon>
    </button>
    <ion-title>Restaurants</ion-title>
  </ion-navbar>

</ion-header>


<ion-content padding class="restaurants attractions common-bg">
  <div class="card round" margin-bottom *ngFor="let restaurant of restaurants" (click)="viewRestaurant(restaurant.id)">
    <div class="card-header" [ngStyle]="{'background-image': 'url(' + restaurant.thumb + ')'}"></div>
    <div class="padding-xs">
      <h5>{{ restaurant.name }}</h5>
      <div class="rating">
        <ion-icon name="md-star" color="restaurant-color" *ngFor="let star of range(restaurant.rating)"></ion-icon>
        <ion-icon name="md-star" color="gray" *ngFor="let star of range(5 - restaurant.rating)"></ion-icon>
        <span color="gray">{{ restaurant.reviews.length }} reviews</span>
      </div>
      <span color="gray">Recommended for:</span>
      <div>
        <div class="pull-left">
          <span color="restaurant-color">{{ restaurant.scores[0].name }},</span>
          <span color="restaurant-color">{{ restaurant.scores[1].name }}</span>
        </div>
        <div class="pull-right">
          {{ restaurant.location.distance }} km
        </div>
        <div class="clear"></div>
      </div>
    </div>
  </div>
</ion-content>

and for restaurants.ts

import {Component} from "@angular/core";
import {NavController} from "ionic-angular";
import {RestaurantService} from "../../services/restaurant-service";
import {RestaurantDetailPage} from "../restaurant-detail/restaurant-detail";


@Component({
  selector: 'page-restaurants',
  templateUrl: 'restaurants.html'
})
export class RestaurantsPage {
  // list of restaurants
  public restaurants;

  constructor(public nav: NavController, public restaurantService: RestaurantService) {
    this.restaurants = restaurantService.getAll();
  }

  // view restaurant detail
  viewRestaurant(id) {
    this.nav.push(RestaurantDetailPage, {id: id})
  }

  // make array with range is n
  range(n) {
    return new Array(Math.round(n));
  }
}

Answer №1

Don't forget to use 'single quotes' around your parameter key.

Give this a shot in the restaurants.ts file

viewRestaurant(id) 
{
    this.nav.push(RestaurantDetailPage, {'id': id})
}

Now, in the restaurant-detail TypeScript:

import { NavController, NavParams} from 'ionic-angular';
export class .... {
    id: any;
    constructor(public navParams: NavParams){
        this.id = this.navParams.get('id');
        console.log(this.id);//You should see the passed id displayed here.    
    }
}

It seems like you might want to pass a 'restaurant' instead of an id here:

<(click)="viewRestaurant(restaurant)">

Answer №2

The reason you are encountering this issue is because you are only passing the restaurant id as a parameter instead of all the restaurant details.

<div class="card round" margin-bottom *ngFor="let restaurant of restaurants" (click)="viewRestaurant(restaurant)">

To resolve this, update your HTML code to pass the entire object data and make sure to send all the data as a parameter to another page when pushing.

 viewRestaurant(restaurant) {
    this.nav.push(RestaurantDetailPage, {id: restaurant})
  }

I hope this clarification aligns with what you were seeking.

Answer №3

import {NavController} from 'ionic-angular';
constructor(private navController: NavController) {

this.navController.push(AnotherPage, {
    val1: 'value1', val2: 'value2'
});
}

AnotherPage :

constructor(private navController: NavController, private navParams: NavParams, private dataService: DataService) {

this.value1 = navParams.get('val1'); 
this.value2 = navParams.get('val2');

}

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Differences between Angular's form builder and form control and form groupIn the

What are the benefits of using form control and form group instead of form builder? Upon visiting this link, I discovered: The FormBuilder simplifies creating instances of a FormControl, FormGroup, or FormArray by providing shorthand notation. It helps ...

Typescript Angular2 filtering tutorial

In Angular 2 using TypeScript, the goal is to search for matching values from an array within an object array. The intention is to filter out any objects where the 'extraService' property contains any of the values from the 'array_values&apo ...

Unloading a dynamically-loaded child component in Vue.js from the keep-alive cache

I have a question that is similar to the one mentioned here: Vue.js - Destroy a cached component from keep alive I am working on creating a Tab System using Vue router, and my code looks something like this: //My Tab component <template> <tab& ...

'Mastering the implementation of promises in React context using TypeScript'

I've been diving into the world of incorporating TypeScript in React and I'm facing a challenge with implementing async functions on context. The error that's popping up reads as follows: Argument of type '{ userData: null; favoriteCoc ...

Adding a fresh element to an array in Angular 4 using an observable

I am currently working on a page that showcases a list of locations, with the ability to click on each location and display the corresponding assets. Here is how I have structured the template: <li *ngFor="let location of locations" (click)="se ...

A simple trick to compile and run TypeScript files with just one command!

Converting TS to JS is typically done using the tsc command, followed by executing the resulting .js file with node. This process involves two steps but is necessary to run a .ts file successfully. I'm curious, though, if there is a way to streamlin ...

Issue: React cannot render Objects as children (received: [object Promise]). If you intended to display multiple children, please use an array instead. (Next)

My dilemma is this: I am trying to display my GitHub repositories on a React component, but I keep encountering the following error: Error: Objects are not valid as a React child (found: [object Promise]). If you meant to render a collection of children, u ...

MatTooltip component in Angular Material UI is malfunctioning

In my angular component within a hybrid application, I have incorporated the mattooltip directive with links. However, I am facing an issue where the tooltip position is not accurate when hovering over the first link. Sometimes, the tooltip appears empty o ...

Using the spread operator to modify an array containing objects

I am facing a challenge with updating specific properties of an object within an array. I have an array of objects and I need to update only certain properties of a single object in that array. Here is the code snippet I tried: setRequiredFields(prevRequir ...

Guide to Conditionally Importing a Module in Angular

I am currently developing a module for Search integration. Instead of directly importing the SearchModule inside my app.module.ts file, I would like to implement a method where an API is called and the SearchModule is imported based on the API response. @N ...

Angular2 Dropdown not updating with values from API

Here is the structure of my project flow: import_product.html <div class="row custom_row"> <div class="col-md-2">Additional Duty: </div> <div class="col-md-2"> < ...

What is the best way to create two MUI accordions stacked on top of each other to each occupy 50% of the parent container, with only their contents scrolling

I am looking to create a layout with two React MUI Accordions stacked vertically in a div. Each accordion should expand independently, taking up the available space while leaving the other's label untouched. When both are expanded, they should collect ...

How can I access a DOM element in an AngularJS 2 TypeScript file?

As a newcomer to AngularJS, I am attempting to add a spinner as a background to all images on my website. Since there are multiple images, using a single variable like isLoaded in the TypeScript file is not feasible. Here is how I am implementing it in th ...

String defines the type

I came across the following code snippet in some external sources that I intend to incorporate into my project: const INIT: 'jsonforms/INIT' = 'jsonforms/INIT' Can someone explain what it means to define a type with a string like INIT ...

Is it possible to upgrade just the rxjs version while keeping all other components at their current versions?

While working on my Angular 4 project, I encountered a problem when trying to use a WebSocket package from GitHub. After running npm install to upgrade the rxjs version, I faced errors. Even after attempting to upgrade just the rxjs version and running ng- ...

What are the steps to lift non-React statics using TypeScript and styled-components?

In my code, I have defined three static properties (Header, Body, and Footer) for a Dialog component. However, when I wrap the Dialog component in styled-components, TypeScript throws an error. The error message states: Property 'Header' does no ...

Tips for setting up a listener for when the month changes in an ion-datetime object

When the user selects a different month, I need to update the highlightedDates by calling a query to retrieve all the dates of that specific month. This currently works if the user manually chooses a month and year using the top button, but not when they c ...

How to manage type mappings while utilizing the spread syntax

In my testing scenario, I am utilizing a setup function and I am looking for a way to pass typing information along when it is called so that I can benefit from intelligence support without having to bypass it in eslint. function setup(): SomeType { retu ...

The state is accurate despite receiving null as the return value

I'm feeling a bit lost here. I have a main component that is subscribing to and fetching data (I'm using the redux dev tools to monitor it and it's updating the state as needed). In component A, I am doing: public FDC$ = this.store.pipe(sel ...

Utilizing a fixed array as the data source for a mat-table

I am currently working on implementing the Angular Material table into my project. I am encountering an issue when trying to define the [dataSource]="data", even though I am using code similar to the examples provided. My question may seem basic, but my t ...