Mastering Angular 7: A guide to efficiently binding values to radio buttons

Struggling to incorporate radio buttons into my project, I encountered an issue where the first radio button couldn't be checked programmatically.

Despite attempting the suggested Solution, it didn't resolve the problem within my code.

Below is the snippet of my radio button implementation:

<div class="col-sm-3 col-form-label" style="padding-right: 0px;">
    <input type="radio" value=1 [checked]="actionUpload == 1" name="uploadAction" [(ngModel)]="actionUpload" (ngModelChange)="choose(1)"> Radio 1
    <input type="radio" value=2 [checked]="actionUpload == 2" name="uploadAction" [(ngModel)]="actionUpload" (ngModelChange)="choose(2)"> Radio 2
</div>

Attached is a peek into my Typescript code:

export class Component   implements OnInit  {
  actionUpload:number = 1


  constructor() { 
       //some code here
  }
  ngOnInit() {
      //some code here

  }


  choose(upT:number){
    this.actionUpload = upT
  }
}

Despite the efforts, the first radio button remains unchecked as per the outcome depicted:

https://i.sstatic.net/3gmy3.png

Any guidance or assistance would be greatly appreciated.

Answer №1

When the value is set to 1, it is interpreted as a string.

If you inspect the HTML element, you will see the following:

<input _ngcontent-tmu-c101="" type="radio" value="1" name="uploadAction" 
  ng-reflect-value="1" 
  ng-reflect-name="uploadAction" ng-reflect-model="1" 
  class="ng-pristine ng-valid ng-touched">

This shows that the value is treated as a string.

It is recommended to use input binding (using square brackets) with [value]="1".

<input
    type="radio"
    [value]="1"
    name="uploadAction"
    [(ngModel)]="actionUpload"
  />
  Radio 1
  <input
    type="radio"
    [value]="2"
    name="uploadAction"
    [(ngModel)]="actionUpload"
  />

View Sample StackBlitz Demo


It appears that using both [checked] and (ngModelChange) alongside [(ngModel)] can lead to redundancy.

It is suggested to choose one of the following options:

  1. [checked] only

  2. [ngModel] and (ngModelChange)

  3. [(ngModel)]

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

An error has occurred with mocha and ts-node unable to locate the local .d.ts file

This is the structure of my project: |_typetests | |_type.test.ts | | myproj.d.ts tsconfig.json Here is how my tsconfig.json file is configured: { "compilerOptions": { "module": "commonjs", "moduleResolution": "node", "lib": ...

Testing Angular 2: Ensuring Component Properly Calls Router with Accurate Arguments

I'm facing an issue with a child component that includes a button element with 'routerlink' attribute for navigation upon clicking. The button does not have a '(click)' handler, only the routerlink. Currently, I am writing a unit ...

Using Bootstrap 4 Datatablejs within an Angular4 CLI project

Just finished developing a web application using Angular 4 and Angular CLI tool. Currently, I am trying to display a table with DataTableJs on one of the pages of my app. However, the styling is not coming out as expected. https://i.stack.imgur.com/H5IIT ...

Unable to retrieve npm repository from GitHub

I've been grappling for approximately 2 hours to integrate a repository into my angular project without success. Here's the link I've been trying: https://github.com/cmelange/ECL-3D-Components#ecl-3d-components. Despite previously having i ...

Load a React component in the same spot when clicked

Is there a way to implement a functionality where clicking on different buttons in a panel will display different components in the same location? <AddNotification /> <EditNotification /> <DeleteNotification /> const AdminPanel = () =& ...

What is the method for adjusting the font size of the label in an Angular mat-checkbox element?

I've been trying to adjust the font size of a mat-checkbox's label, but no matter what I do, the component's default styles keep overriding my changes: Using !important Trying ::ng-deep Applying a global style in styles.scss <mat-checkb ...

Encountering a problem with Angular 11 SSR after compilation, where the production build is causing issues and no content is being displayed in

{ "$schema":"./node_modules/@angular/cli/lib/config/schema.json", "version":1, "newProjectRoot":"projects", "projects":{ "new-asasa":{ "projectType": ...

Unable to assign to 'options' as it is not recognized as a valid property of 'p-multiSelect'

I am currently in the process of incorporating the datatable filter from primeng into my project. Here is the code snippet I have written: <p-column field="time" header="Time" [filter]="true" filterPlaceholder="&#xf0b0;"> <ng-template pTe ...

What is the correct version compatibility matrix for Expo, NPM, Node, React Native, and TypeScript?

Currently, I am in the process of setting up React Native with TypeScript. Here are the steps I followed: npx react-native init MyApp --template react-native-template-typescript I made sure to install TypeScript as well: npm install -g typescript ' ...

What is the most efficient way to iterate through an array to push properties into an object nested within another array?

I have been working on a small Angular application that functions as a scheduler, allowing users to input a Name, Start and End dates, and toggle a boolean checkbox through a form. One challenge I am facing is trying to assign the names entered by each use ...

Angular - Dropdown menu fails to display options

I encountered an issue with the JSON response from my Angular-12 API endpoint: { "message": "vehicle Model Detail.", "error": false, "code": 200, "results": { "vehiclemakes": [{ ...

Exploring the use of .pipe with Angular Jest for testing

Currently, I am trying to test the following .ts file: create(entityResourceID, params: any): Observable <any>{ const url = `${this.apiUrl}/${entityResourceID}/assignee`; return this.http.post(url, params).pipe( map(() ...

Exploring the method to implement unit testing for a nested if condition using Karma-Jasmine within an Angular environment

I have a function and my unit test coverage is currently at 75%, but I am aiming for 100% coverage. This is the function in question: calculateRatingSummary(): void { if (this.averageRating > 0) { this.avgRatings = Math.trunc(this.averageRat ...

Managing the dispatch of a successful action in a component

In my component, I have a form that adds items to a list. Once an item is successfully added, I want to reset the form using form.resetForm();. However, I am struggling to determine when the action of adding the item has been successful. I attempted to sub ...

After the assignment, TypeScript reordered the elements of the array

Dealing with an array of objects for use in a ngFor loop has presented a challenge. The issue arises when the order that was initially set for the array changes unexpectedly due to JavaScript manipulation. Originally, the array is ordered as expected when ...

Testing the Click() function in Angular2 using keypress event

I am currently working on testing a sorting feature for a table. This particular table allows for sorting based on both a primary and secondary value, with the secondary value being selected by holding down the shift key. In order to set the sort order, I ...

When the promise is resolved, the members of the AngularJS controller are now

I'm experiencing some unexpected behavior in my controller when executing a certain method. The code snippet looks something like this: this.StockService.GetByInvoicesID(this.SelectedInvoice.ID).success((StockItems) => { this.StockItems = Stoc ...

Parent Class implementation for dynamic loading of components

I have been working on creating a new code for dynamic component loading using a parent-child relationship. The child component is set to override the parent and will be used for dynamically loading components. I found this useful link that guided me throu ...

Can someone please explain the significance of these three lines in the Angular file App module.ts?

This pertains to an Angular file called appmodule.ts <pre> import { NgModule } from '@angular/core'; import { BrowserModule } from '@angular/platform-browser'; import { UploadModule } from '@progress/kendo-angular-upload&ap ...

Issue: In an Angular electron app, a ReferenceError is thrown indicating that 'cv' is

I have been working on a face detection app using OpenCv.js within an Angular electron application. To implement this, I decided to utilize the ng-open-cv module from npm modules. However, when attempting to inject the NgOpenCVService into the constructor ...