A step-by-step guide on setting the default selection for the initial ionic radio button using Angular

Could someone assist me in pre-selecting the initial radio button from a list of generated radio buttons that can be updated if the user selects a different radio button?

I am encountering an error with my current implementation:

TypeError: Cannot read properties of undefined (reading '0')

delivery-dates.model.ts

export interface DeliveryDates {
  color: string;
  date: string;
  date_name: string;
}

cart.page.ts code:

export class CartPage implements OnInit, OnDestroy {
  dates: DeliveryDates[];
  selectedValue: any;
  private datesSubscription: Subscription;

  constructor() {
  }

  ngOnInit() {
    this.getDeliveryDates();
    this.selectedValue = this.dates[0].date;
  }

  getDeliveryDates() {
    this.datesSubscription =
      this.cartService.getDeliveryDates().subscribe(
        data => {
          this.dates = data;
        },
        error => {
          console.log('Error', error);
        });
  }
}

cart.page.html

<ion-list class="dates-list">
  <ion-radio-group value="{{dates[0]}}"  [(ngModel)]="selectedValue">
    <ion-item *ngFor="let datum of dates;let i = index" (click)="modal.dismiss()">
      <ion-icon name="today-outline"></ion-icon>
      <ion-label class="{{datum.color}}">{{datum.date_name}} {{ datum.date }}</ion-label>
      <ion-radio slot="end" value="{{ datum.date }}"></ion-radio>
    </ion-item>
  </ion-radio-group>
</ion-list>

Answer №1

Have you considered trying out this code snippet? It seems like you're attempting to initialize a value at startup, but the assigned value should be fetched beforehand.

export class CartPage implements OnInit, OnDestroy {
  dates: DeliveryDates[];
  selectedValue: any;
  private datesSubscription: Subscription;

  constructor() {
  }

  ngOnInit() {
    this.retrieveDeliveryDates();
  }

  retrieveDeliveryDates() {
    this.datesSubscription =
      this.cartService.fetchDeliveryDates().subscribe(
        data => {
          this.dates = data;
          (this.dates.length>0)?this.selectedValue = this.dates[0].date:false;
        },
        error => {
          console.log('Error', error);
        });
  }
}

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

Conceal the div element if the value exceeds 0

I'm looking for a way to display a div when the number of remaining days is less than 0. I got it working on jsfiddle, but for some reason, it doesn't work anywhere else. if ($('.daysrem&a ...

What is the reason for the HTTP service being activated automatically?

Utilizing the Http service, data is fetched and then passed into the cached service. The component subscribes to the cached service and initiates the HTTP request. The HTTP GET service is intended to be called when the user clicks on an anchor tag. Upon c ...

Only initiate the loading of the iframe within the div upon clicking a specific element

Is there a way to delay loading the content of a div until it's clicked, instead of having all data loaded at once when the page loads? I noticed that removing unnecessary divs made the page load much faster. How can I prevent all data from being loa ...

Maximizing the potential of Next JS 13 Server Components

Exploring the updates in Next JS 13, I have found it intriguing that every component is now a server component by default. This concept has been puzzling for me as I try to grasp how to effectively leverage this feature. For instance, my current challenge ...

ReactJS - Opt for useRef over useState for props substitution

Presented below is my ImageFallback component, which serves as a backup by displaying an svg image if the original one is not available. export interface ImageProps { srcImage: string; classNames?: string; fallbackImage?: FallbackImages; } const Im ...

Error Uncovered: Ionic 2 Singleton Service Experiencing Issues

I have developed a User class to be used as a singleton service in multiple components. Could you please review if the Injectable() declaration is correct? import { Injectable } from '@angular/core'; import {Http, Headers} from '@angular/ht ...

Multiple subscriptions to a Typescript service in an AngularJS controller have caused an issue with unsubscribing from it

Issue at Hand: I am currently working on merging AngularJS with Angular by creating components and services to be used within an AngularJS controller. The AngularJS Controller is initiated through $routeProvider. One of the components I have created is a ...

Utilizing a .ini file to assign variables to styles elements in Material-UI: A comprehensive guide

I need to dynamically set the background color of my app using a variable retrieved from a .ini file. I'm struggling with how to achieve this task. I am able to fetch the color in the login page from the .ini file, but I'm unsure of how to apply ...

What is the reason that the <script> tag cannot be directly inserted into the .html() method?

As I continue to learn front-end development, I've created my own version of JS Bin. When the 'run' button is clicked, a statement is executed to showcase the HTML, CSS, and JavaScript in an iframe (the output window): ("iframe").contents() ...

Angular 2+ NgOnInit sets a value for an input array, however, it results in an error message stating that

One of the components in my application requires specific inputs, with the feedList being the most important one. Within the feedList, there are feed objects containing various data fields. However, some of these fields may be undefined depending on the fe ...

Send the chosen item from the <b-form-select> element to the parent component through props

Using Vue.js, I have successfully created a form where all input fields pass their values except for the <b-form-select> element. How can I pass the value of the selected option in <b-form-select> to the parent component? Child Component: < ...

Setting the z-index for data points in a scatter plot on HighCharts

Utilizing HighCharts to display a large number of points on a plot. Each point has an opacity setting and changes to red when selected. However, some points are difficult to distinguish due to overlapping. I would like the selected point to be easily visi ...

Issue encountered while utilizing Mongoose ArrayFilters for updating a nested subdocument

I am working with a Mongoose collection and need to update a nested subdocument within it. Here is the basic structure: The collection has a parent entry (Map) This entry contains an array of children (Phases) Each child has one or more grandchildren (S ...

Is there a way to effectively alter an object that has been assigned in a separate file?

Seeking Assistance: I am facing an issue in my current project where I need to store a javascript object in an external file and then export it using module.exports. The challenge now is that I want another file to be able to modify a specific value withi ...

The `modelName` model cannot be recompiled as it has already been written

Issue with Updating partnerCode Model After Compilation. I have a file called models/partnerCode.js var mongoose = require('mongoose'); var Schema = mongoose.Schema; var partnerCodeSchema = new Schema({ email: String, used: {type: Numb ...

javascript guide on converting an array into the correct JSON format

I'm working with an array that has the following structure: var arr = [ [{a:1}], [{b:1}], [{c:1}], [{d:1}], [{e:1}] ] My goal is to format it into the proper format as shown below: [{a:1},{b:1},{ ...

Javascript code fails to execute properly on IE8

I have a scenario where I am working with two drop-down menus. When the user selects an option from one menu, it should dynamically change the options in the other menu. However, I'm facing an issue with Internet Explorer where the second drop-down me ...

Revamping FullCalendar: Strategies for refreshing or initializing FullCalendar anew or efficiently adding multiple events at once

I attempted to batch add new events to the calendar but failed to find a convenient method to do so. As a result, I decided to reinitialize the view with a new events array. Here's what I tried: var events = [ { title: 'Conference&ap ...

Passing a MySQL connection to scripts in Express

After setting up the mysql connection with all the required parameters in app.js, is there a way to make it accessible to other scripts in routes/ without having to redeclare or require the mysql parameters again, simply by using client.query(..)? ...

Use the Nodejs HTTP.get() function to include a custom user agent

I am currently developing an API that involves making GET requests to the musicBrainz API using node.js and express. Unfortunately, my requests are being denied due to the absence of a User-Agent header, as stated in their guidelines: This is the code sn ...