Troubleshooting ion-radio loop error in Ionic 2

I am encountering an issue with the ion-radio component in Ionic 2.

The problem is that when the component retrieves data from a service using HTTP and assigns it to the data property within the ngOnInit lifecycle hook, the radio buttons are not able to be selected.

Template:

<ion-list class="rooms" padding radio-group>
    <ion-item *ngFor="let r of data?.rooms">
       <ion-label >{{ r?.name }}</ion-label>
       <ion-radio [checked]="selectedRoom == r?.id" [value]="r?.id"></ion-radio>
    </ion-item>
</ion-list>

Component:

import { Component, OnInit } from '@angular/core';
import { NavController, NavParams } from 'ionic-angular';

import { BookConfirmPage } from '../bookconfirm/bookconfirm';
import { RoomDetailPage } from '../roomdetail/room';

import { HotelService } from '../../providers/hotel/hotelservice';

@Component({
  selector: 'page-hotel-detail',
  templateUrl: 'hotel.html',
  providers: [HotelService]
})
export class HotelDetailPage implements OnInit {

  public data;
  public selectedRoom: number;

  constructor(
    private navCtrl: NavController,
    private hotelServ: HotelService,
    private navParams: NavParams
    ) { }

  ngOnInit(): void {
    // You need an interface to make the data readable and consistent.
    // This method is not recommended for production. For learning purposes only.
    let id = this.navParams.get('id');
    let idRoom = this.navParams.get('idRoom');

    this.hotelServ.get(id).then(res => {
      this.data = res;
      //console.log(res);
    })
    .catch(err => console.log(err));

    this.selectedRoom = idRoom;
  }

  showBookConfirm(id) {
    console.log(this.selectedRoom)
    this.navCtrl.push(BookConfirmPage, { 'id': id });
  }

  showRoomDetail(id) {
    this.navCtrl.push(RoomDetailPage, { 'id': id });
  }

}

Edited: This is simply an interpolation issue in my code. Just change the template to use [value]="r?.id".

Answer №1

Simply make a modification

<ion-list class="rooms" padding radio-group>
  <ion-item *ngFor="let r of data?.rooms">
    <ion-label >{{ r?.name }}</ion-label>
    <ion-radio checked="{{ selectedRoom == r?.id }}" value="{{ r?.id }}"></ion-radio>
  </ion-item>
</ion-list>

to turn it into

<ion-list class="rooms" padding radio-group [(ngModel)]="selectedRoom">

  <ion-card class="room-card" *ngFor="let r of data?.rooms">
    <ion-card-content>
      <div class="left">
        <ion-radio [value]="r?.room_id"></ion-radio>
      </div>
      <div class="right" (click)="showRoomDetail(r?.room_id)">
        <ion-card-title>
          {{ r?.name }} {{ r?.room_id }}
        </ion-card-title>
        <p color="warning">&nbsp;Rp. {{ r?.cost }}</p>
      </div>
    </ion-card-content>
  </ion-card> 

</ion-list>

This problem stems from an interpolation issue within my code, rather than a flaw in Ionic.

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

Is it possible to utilize an array of numbers as a data source in ng2-smart table?

Hey there, I'm currently facing an issue with populating ng2-smart-table with an array of numbers. When I try to display the table, all I see is 6 empty rows like this: https://i.stack.imgur.com/DZJjq.png Here's the code for the table: <ng2- ...

Tips for managing Typescript Generics while utilizing the styled function provided by the '@mui/material/styles' package

import Table,{TableProps} from 'my/table/path' const StyledTable = styled(Table)({ ...my styles }) const CustomTable = <T, H>(props: TableProps<T, H>) => { return <StyledTable {...props} /> } This is the issue I encoun ...

Currently, I'm harnessing the power of TypeScript and React to identify and capture a click event on a dynamically generated element within my document

Is there a way to detect a click on the <p> tag with the ID of "rightDisplayBtn"? I've tried using an onclick function and event listener, but neither seem to be working as expected. function addDetails() { hideModal(); addBook ...

Encountering issues with Typescript Intellisense not functioning properly with root directory imports specified with the @

I am facing a challenge where TypeScript/Intellisense is unable to determine types when importing using the @ symbol with my compilerOptions set to the root directory: When I use ../, types are visible clearly: The compilerOptions parameters are configur ...

Angular Elements generates compact, single-line HTML output

It's incredibly frustrating how browsers handle inline-block elements, creating invisible margins when placed side by side. You can experience this "bug" firsthand here: http://jsfiddle.net/8o50engu/ Interestingly, if these elements are on the same l ...

Strange occurrences with HTML image tags

I am facing an issue with my React project where I am using icons inside img tags. The icons appear too big, so I tried adjusting their width, but this is affecting the width of other elements as well. Here are some screenshots to illustrate: The icon wit ...

The content within the mat-card-content paragraph exceeds the boundaries of the mat-card container,

I recently began working with Angular Material and came across an issue. When I have a shorter text paragraph, it overflows the card. However, when I use a larger paragraph, the text wraps nicely. Here is the code snippet: <mat-card *ngFor="let s ...

Why is there a false positive in the onChange event for the number type in React TypeScript?

I encountered an error on line 24 Argument of type 'string' is not assignable to parameter of type 'SetStateAction'.ts(2345) This issue occurred while working with TypeScript for a React experiment. const App: React.FC = () => ...

Maintaining scroll position in React Router v6

My website's homepage displays a user's feed. When a user clicks on one of the feed cards, they are taken to a different URL. However, when the user returns to the homepage, it automatically scrolls to the top. I am looking for a way to preserve ...

Tips on preventing state sharing in Angular applications

Delving into the world of Angular has presented me with an intriguing issue. I've crafted a component dedicated to displaying a dialog, complete with its own template (HTML), CSS, and TypeScript files. Whenever a user clicks on an item within a list ...

What is the process for moving information between files?

I have two files which are named as, employee-rates-controller.ts: private load() { return this.entityService .load(this.$scope.projectRevisionUid) .then(resp => { localStorage.removeItem('employeerates'); this.$ ...

Protractor syncing with an Angular page following redirection to an Auth0 non-Angular page

My Angular web application utilizes Protractor for end-to-end tests. Recently, I implemented OAuth0 authentication into my app. To disable Angular synchronization before redirecting to the non-Angular OAuth0 page, I use await browser.waitForAngularEnabled( ...

Simple steps to transform the "inputs" syntax into the "@Input" property decorator

There's this code snippet that I need to modify: @Component({ selector: 'control-messages', inputs: ['controlName: control'], template: `<div *ngIf="errorMessage !== null">{{errorMessage}}</div>` }) Is the ...

Discovering how to specify the type of a dynamically created object using 'for await' in TypeScript

for await (user of users) { ... } Encountered an issue: "error TS2552: Cannot find name 'user'. Did you mean 'users'?" Appreciate your assistance. ...

I'm looking to switch out the `~` to turn it into a URL for the backend, seeing as `<img alt="" src="~/media/Banner/plane.JPG">` is returning a 404 error

1. Received an HTTP Request and JSON response from the backend localhost:3000 (entered value using wysiwyg) { "Description": "&lt;img alt=&quot;&quot; src=&quot;~/media/Banner/plane.JPG&quot; /&gt;1 test berita&lt ...

What's the issue with conducting a unit test on a component that has dependencies with further dependencies?

I am experiencing an annoying error that seems to be my mistake and I cannot figure out how to resolve it. The issue lies within a simple component which serves as a top-bar element in my web application. This component has only one dependency, the UserSe ...

Generate a new entry by analyzing components from a separate array in a single line

I have a list of essential items and I aim to generate a record based on the elements within that list. Each item in the required list will correspond to an empty array in the exist record. Essentially, I am looking to condense the following code into one ...

TypeScript allows for the declaration of a function that includes a mandatory property within the function signature

If I desire a tagged function with an interface such as: interface TaggedFun { (args): void; tag: boolean; } It appears that declaring a function to match this signature is not possible (since any function literal will lack the mandatory tag prop ...

Error Alert: Next.js TypeScript is reporting that the necessary packages are missing from your setup

As I work on developing a basic Next.js website using their TypeScript starter, everything was going smoothly with the 'yarn dev' command. However, out of nowhere, I started encountering an error message whenever I tried to run 'yarn dev&apo ...

Matching utility types and themes in Tailwind CSS

I encountered an issue while trying to implement the Tailwind plugin in my project. It seems that a TypeScript error has occurred. I'm curious about the data types of matchUtilities and themes. Can someone provide some insight? const plugin = require( ...