Search code examples
angulartypescriptradio-buttonangular7angular-forms

Angular 7 - How to bind the value to the radio button


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 Solution, but it is still not working in my code.

Here is my radio button:

<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>

and below is my Typescript:

export class Component   implements OnInit  {
  actionUpload:number = 1


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

  }


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

Here is the result I got, radio 1 is never checked.

enter image description here

Am I missing something??

I would be glad for any help.


Solution

  • 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" 
      class="ng-pristine ng-valid ng-touched">
    

    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)]