Updating array values using radio buttons in Angular: A step-by-step guide

I am creating an array of phone objects where each phone is assigned a role, either main or secondary. I want to be able to update the main phone using a radio button and have it reflect in my object list. Here is my code:

HTML

<section *ngFor="let phone of phoneList; let index = index">
    <!-- test 1 -->
    <input [checked]="phone.phoneRole==='main'" type="radio" id="phoneTest{{index}}" name="phoneRoleTest">
    <!-- test 2 -->
    <input [(ngModel)]="phone.phoneRole" type="radio" id="phone{{index}}" name="phoneRole">
    <form >
        <input id="phoneNumber{{index}}" [disabled]="true" value="{{phone.phoneNumber}}">
        <button [disabled]="phone.phoneRole==='main'" (click)="editPhone(phone)">edit</button>
        <button type="button" [disabled]="phone.phoneRole==='main'" (click)="deletePhone(phone)">x</button>
    </form>
</section>

<form (ngSubmit)="f.form.valid && onAddPhone()" #f="ngForm">
    <label for="phoneNumberInput">Phone Number:</label>
    <input required class="m-1 col-md-2" type="tel" name="tel" id="phoneNumber" placeholder="Phone number" [(ngModel)]="phoneNumberInput">
    <button>+</button>
</form>

Component TS

export class CreateCustomerComponent implements OnInit {
  phoneNumberInput: string = '';
  phoneList: PhoneNumber[] = [];
  phoneIndex: number = 0;

  phoneRole: string = 'main';

  constructor(private phoneService: PhoneService) {}

  ngOnInit(): void {
    // set the phoneList from the service to the local phoneList
    this.phoneList = this.phoneService.phoneList;
  }

  create(){

  }
  onAddPhone() {
    // create first obj
    if (this.phoneList.length < 1) {
      var newPhone = new PhoneNumber(this.phoneNumberInput, this.phoneRole);
    } else {
      // create new obj phoneNumber
      this.phoneRole = 'secondary';
      var newPhone = new PhoneNumber(this.phoneNumberInput, this.phoneRole);
    }
    // add phoneNumber to phoneList
    this.phoneService.addPhone(newPhone);
  }

  editPhone(phone: PhoneNumber) {
    if (phone.phoneRole === 'main') {
      alert('No editable');
    } else {
    }
  }

  deletePhone(phoneNumber: PhoneNumber) {
    this.phoneService.delete(phoneNumber);
  }
}

Service TS

import { PhoneNumber } from "./phoneNumber.component";

export class PhoneService{

    phoneList: PhoneNumber[]=[];

    addPhone(newPhone:PhoneNumber){
        // add phoneNumber to phoneList
        this.phoneList.push(newPhone);
    };

    delete(phoneNumber: PhoneNumber){
        // delete phoneNumber of the phoneList
        const index: number = this.phoneList.indexOf(phoneNumber);
        this.phoneList.splice(index,1);
    };

}

I would like to know if it is possible to set the main phone in my objects array using a radio button. Thank you for your time!

Answer №1

I discovered an effective method for updating the array of phone objects with a specific structure

Here is the HTML code for the radio button:

<input
        [checked]="phone.mainPhone && !phone.editPhone"
        [disabled]="phone.editPhone"
        (change)="radioChangeHandler(index)"
        type="radio"
        id="phoneTest{{ index }}"
      />

This is the TypeScript function for handling the radio button:

// Function to set the main phone
  radioChangeHandler(index: number) {
    if (!this.phoneList[index].editPhone) {
      for (let index = 0; index < this.phoneList.length; index++) {
        this.phoneList[index].mainPhone = false;
      }
      this.phoneList[index].mainPhone = true;
    } else {
      alert('You must save the changes in the phone before selecting it as the main phone');
    }
  }

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

Converting Angular5 HttpClient Response into Numeric Values

Currently, I'm working on incorporating a real-time CPU usage chart into my project. However, I'm facing some issues in extracting the value itself from the Observable. The get call I am using returns a single number. Ideally, I would like to di ...

Determine to which observable in the list the error corresponds

const obs1$ = this.service.getAllItems(); const obs2$ = this.service.getItemById(1); combineLatest([obs1$, obs2$]) .subscribe(pair => { const items = pair[0]; const item = pair[1]; // perform actions }, err => { // det ...

When deploying, an error is occurring where variables and objects are becoming undefined

I've hit a roadblock while deploying my project on Vercel due to an issue with prerendering. It seems like prerendering is causing my variables/objects to be undefined, which I will later receive from users. Attached below is the screenshot of the bui ...

typescript: tips for selecting a data type within an object

I need help extracting the type of the 'name' property from an object belonging to the Action interface. interface Action { type: string, payload: { name: string } } I attempted to use Pick<Action, "payload.name">, but it didn&apos ...

Using TypeScript with React may result in an error message stating that a string cannot be assigned to a parameter of type 'keyof T'

I've encountered an issue with my sorting function that I built using TypeScript and React Hooks. The error message I'm getting is: Argument of type 'string' is not assignable to parameter of type 'keyof T'. Type 'stri ...

Enhance your coding experience with Angular Apollo Codegen providing intelligent suggestions for anonymous objects

Currently, I am exploring the integration of GraphQL with Angular. So far, I have been able to scaffold the schema successfully using the @graphql-codegen package. The services generated are functional in querying the database. However, I've noticed ...

What is the best way to conceal an element solely in live production environments?

Is there a way in my Angular code to specifically target the PROD environment? <div *ngIf="environment !== 'prod'" class="col-6"> <button class="btn btn-primary text-white add-photo" (cli ...

Methods for opening ngx-daterangepicker-material outside of a button/icon when there are multiple date range pickers in the same form

Is there a way to open ngx-daterangepicker-material by clicking outside of any button or icon? I am aware that ngx-daterangepicker-material allows this functionality through the use of @ViewChild(DaterangepickerDirective, { static: false }) pickerDirective ...

Why should TypeScript interfaces be utilized in Angular services for defining type information?

What are the benefits of creating an interface for an Angular service as opposed to simply exporting the service class and using that for type information? For example: class Dashboard { constructor(ui: IUiService){} } vs class Dashboard { cons ...

Overloading TypeScript functions with Observable<T | T[]>

Looking for some guidance from the experts: Is there a way to simplify the function overload in the example below by removing as Observable<string[]> and using T and T[] instead? Here's a basic example to illustrate: import { Observable } from ...

Typescript types for React Native's SectionList: A comprehensive guide

Currently, I am in the process of developing a React Native app using TypeScript. In order to display information in a structured manner, I decided to implement a SectionList. Following the official documentation, I have written the following code snippet: ...

Having trouble establishing a connection with Db2 while using protractor

Encountering an issue when attempting to establish a connection with a remote DB2 database, resulting in the following exception: SQL30081N A communication error has been detected. The communication protocol in use is 'TCP/IP'. The com ...

Error in VueJS/Typescript: Module 'my-module' or its type declarations are not found

Hey fellow developers! I'm currently working on a Vue2 setup with Nuxt and Typescript. I'm facing an issue while trying to install the awesome vue-slick-carousel module via yarn. When attempting to import the module in my component, Typescript th ...

Learn the steps to assign a Base64 URL to an image source

I am currently facing an issue with an image that is being used with angular-cli: <img src="" style="width: 120px; padding-top: 10px" alt="" id="dishPhoto"> The image has a Base64 url named imgUrl. My intention is to set the image source using the ...

Can storing JWT in the windows object be considered a secure method for easy retrieval when required?

I have received an access token (JWT) in the URL. For example: . Is it secure to save this token in the window object? For instance: window.jwt = Token If so, how can it be utilized (extracting the JWT from the Window object and carrying out subsequent ...

What is the best way to create an Office Script autofill feature that automatically fills to the last row in Excel?

Having trouble setting up an Excel script to autofill a column only down to the final row of data, without extending further. Each table I use this script on has a different number of rows, so hardcoding the row range is not helpful. Is there a way to make ...

Launching in dynamically loaded modules with bootstrapping

The Angular Guide explains that during the bootstrapping process, components listed in the bootstrap array are created and inserted into the browser DOM. However, I have noticed that I am unable to bootstrap components in my lazy loaded feature modules. E ...

What are the steps to utilize kendo-fileselect in order to upload files from an Angular application to a C# web API?

We are integrating Kendo for Angular into our current project. In our existing system, we utilize kendo-upload which triggers a server call immediately. However, we cannot follow the same approach for this particular page. https://i.stack.imgur.com/qdn2b. ...

The TypeScript inference feature is not functioning correctly

Consider the following definitions- I am confused why TypeScript fails to infer the types correctly. If you have a solution, please share! Important Notes: * Ensure that the "Strict Null Check" option is enabled. * The code includes c ...

Tips for updating a JSON object value in Node.js

Storing a JSON object in a JSON file is important for passing data during an API call. To update the object, replace "it-goes-here" with the following {} block. Newly updated data: { "parenturl":"xxx.com", "user ...