Javascript 我想得到一个有角度的单选按钮的值

Javascript 我想得到一个有角度的单选按钮的值,javascript,angular,typescript,Javascript,Angular,Typescript,我想从我的单选按钮中获取值,特别是已选择的单选按钮。我确实尝试通过以下代码来实现: my home.component.html <span>Categories</span> <input type="button" onclick="alert($('input[name=category]:checked').attr('id'))" value="click me too" /> <div id="categorybo

我想从我的单选按钮中获取值,特别是已选择的单选按钮。我确实尝试通过以下代码来实现: my home.component.html

<span>Categories</span>
        <input type="button" onclick="alert($('input[name=category]:checked').attr('id'))" value="click me too" />
      <div id="categorybox">
      <tr  class="categories" *ngFor="let category of categories">
        <td>
          <input type="radio"  id={{category.category}} name="category" value="{{category}}"/>
          <label for ={{category.category}} >{{category.categoryName}}</label>
        </td>
      </tr>

    </div>

您可以绑定单选按钮的数据

<input type="radio" [(ngModel)]="selectedCategory" name="category" value="{{category.category}}"
(change)="Category($event)"/>

您应该绑定收音机并添加单击事件。另外,我认为你的名字对于你的输入来说不是唯一的

在TS中:

<input type="radio"  id={{category.category}} [(ngModel)]=selectedCategory name="{{category.categoryName}}" value="{{category}}" (click)=selectCategory(category)/>

您应该在Angular中使用
ngModel
,以获取所选单选按钮的值。请看第一个答案中的示例:这里的代码太多,我不清楚您希望做什么。在这里只转储一堆代码是不好的-您需要首先尝试在一个最小的示例中重现问题,这样无关的代码就不会使问题变得混乱。我尝试了这个方法,但没有得到我得到的值:值是:事件{isTrusted:true,键入:“change”,目标:input.ng untouched.ng pristine.ng valid..}似乎您需要访问事件对象的
目标
成员。在打印的事件对象中,是否有名为
target
的成员?你能试试这个方法吗:
Category($event){console.log($event.target.value);}
我得到错误类型错误:无法读取我的控制台中未定义的属性'value'你以前得到的完整输出是什么?event{isTrusted:true,键入:“change”,target:input.ng-untouched.ng-pristine.ng-valid,currentTarget:input.ng-untouched.ng-pristine.ng-valid,eventPhase:2,…}气泡:true cancelBubble:false cancelable:false Composited:false currentTarget:null defaultPrevented:false eventPhase:0 isTrusted:true路径:(14)[input.ng-valid.ng-dirty.ng-touch,td,tr.categories,div#categorybox,div#category.collapse.show,div.col-sm.main,div.row,div.container-fluid,app home,app root,body,html,document,Window]returnValue:true srcElement:input.ng-valid.ng-dirty.ng-touchedIt可以工作,但它选择了我所有的按钮,我不希望这样。它是否只选择了一个按钮?当我单击一个单选按钮时,它选择了所有的类别。我只想选择一个类别。类别是唯一的,因为只有一个类别没有重复项。对不对你的答案是选择了我所有的单选按钮。这意味着你的模型有问题。我可能会使用id来保存我的值。所以bind将变成{{selectedCategoryId}},而值将是{{category.id}
Category(value) {
    console.log(" Value is : ", value );
}
<input type="radio"  id={{category.category}} [(ngModel)]=selectedCategory name="{{category.categoryName}}" value="{{category}}" (click)=selectCategory(category)/>
export class HomeComponent implements OnInit {
   public selectedCategory: Category

   public selectCategory (category) {
      // do something here
      // this.selectedCategory will be the selected value
      // the category will be the value that was just selected
   }