简体   繁体   English

Angular 7 - 如何将值绑定到单选按钮

[英]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:以下是我的 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.这是我得到的结果,收音机 1 从未被检查过。

在此处输入图像描述

Am I missing something??我错过了什么吗?

I would be glad for any help.我会很高兴有任何帮助。

With value=1 , it treats the value as a string.使用value=1 ,它将值视为字符串。

You can inspect the HTML element and would get this您可以检查 HTML 元素并得到这个

<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" .您应该使用带有[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 示例 StackBlitz 演示


While I think [checked] and (ngModelChange) seem to duplicate (function) when you have used the [(ngModel)] (two-way binding).当您使用[(ngModel)] (双向绑定)时,我认为[checked](ngModelChange)似乎重复 (function)。

Either you should use (only) one of these:您应该(仅)使用其中之一:

  1. [checked] or [checked]

  2. [ngModel] and (ngModelChange) or [ngModel](ngModelChange)

  3. [(ngModel)]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM