Home > OS >  Angular 7 - How to bind the value to the radio button
Angular 7 - How to bind the value to the radio button

Time:08-04

I'm trying to use the radio button on my project but I failed to check the first radio button programmatically.

I had tried the enter image description here

Am I missing something??

I would be glad for any help.

CodePudding user response:

With value=1, it treats the value as a string.

You can inspect the HTML element and would get this

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

which you would see the value become a string.

You should use the input binding (the square bracket) with [value]="1".

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

Sample StackBlitz Demo


While I think [checked] and (ngModelChange) seem to duplicate (function) when you have used the [(ngModel)] (two-way binding).

Either you should use (only) one of these:

  1. [checked] or

  2. [ngModel] and (ngModelChange) or

  3. [(ngModel)]

  • Related