【问题标题】:I want to get the value of a radio button with Angular我想用 Angular 获取单选按钮的值
【发布时间】:2020-01-31 17:33:42
【问题描述】:

我想获得我的单选按钮的值,特别是已选择的那个。我确实尝试通过以下代码来做到这一点: 我的 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>

我在弹出窗口中变得不确定,我不知道为什么。我想使用 id 将信息传递给 http 请求,以便我可以按类别显示我的产品。我希望它从我的 api 链接到我的类别列表,这样当我添加一个类别时,它就会显示为单选按钮。我只需要通过我的函数来获得那个值。代码在 html 中以提高可读性。我想在单击按钮时获取按钮的值。

我的 home.component.ts

import { Component, OnInit } from '@angular/core';
import {Home} from '../model/Home';
import {HomeService} from '../service/Home.service';
import {Category} from '../model/Category';
import {CategoryService} from '../service/Category.service';
declare var $: any;
@Component({
  selector: 'app-home',
  templateUrl: './home.component.html',
  styleUrls: ['./home.component.css']
})
export class HomeComponent implements OnInit {
  page= 0;
  home: Home[];
  categories: Category[];

  constructor(private homeService: HomeService,private categoryService: CategoryService) { }

    Category($event){


    }


  SortPrice($event:any){
    let icon = document.getElementById("asc-desc1");
    if(icon.className === "fas fa-angle-down"){
      icon.className ="fas fa-angle-up";
      this.homeService.getByPriceAsc().subscribe(data => {
      this.home = data;
    });
    }else{
      icon.className ="fas fa-angle-down"
      this.homeService.getByPriceDesc().subscribe(data => {
        this.home = data;
      });
    };

  }

  SortSale($event:any){
    let icon = document.getElementById("asc-desc2");
    if(icon.className === "fas fa-angle-down"){
      icon.className ="fas fa-angle-up";
      this.homeService.getBySaleAsc().subscribe(data => {
      this.home = data;
    });
    }else{
      icon.className ="fas fa-angle-down"
      this.homeService.getBySaleDesc().subscribe(data => {
        this.home = data;
      });
    };

  }
  SortDiscount($event:any){
    let icon = document.getElementById("asc-desc3");
    if(icon.className === "fas fa-angle-down"){
      icon.className ="fas fa-angle-up";
      this.homeService.getByDiscountAsc().subscribe(data => {
      this.home = data;
    });
    }else{
      icon.className ="fas fa-angle-down"
      this.homeService.getByDiscountDesc().subscribe(data => {
        this.home = data;
      });
    };

  }

  ngOnInit() {

      this.homeService.getAll().subscribe(data => {
      this.home = data;
    });
    this.categoryService.getAll().subscribe(data => {
      this.categories = data;
    });

  }

}

【问题讨论】:

  • 您应该在 Angular 中使用 ngModel 来获取选定单选按钮的值。在此处查看第一个答案中的示例:stackoverflow.com/questions/42443903/…
  • 这里的代码太多,我不清楚你想做什么。在这里只转储一堆代码是不好的——你需要先尝试在一个最小的例子中重现问题,所以不相关的代码不会混淆问题。

标签: javascript angular typescript


【解决方案1】:

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

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

然后在你的 TypeScript 文件中捕获事件;或者你可以使用模型selectedCategory

Category(value) {
    console.log(" Value is : ", value );
}

【讨论】:

  • 我试过了,但我没有得到我得到的值:值是:事件 {isTrusted:true,类型:“change”,目标:input.ng-untouched.ng-pristine.ng -有效..}
  • 看来您需要访问事件对象的target 成员。在打印的事件对象中,是否有一个名为 target 的成员?你可以试试这个方法吗:Category($event) { console.log($event.target.value); }
  • 我收到 ERROR TypeError: Cannot read property 'value' of undefined in my console
  • 你之前得到的完整输出是什么?
  • 事件 {isTrusted: true, type: "change", target: input.ng-untouched.ng-pristine.ng-valid, currentTarget: input.ng-untouched.ng-pristine.ng-有效,eventPhase:2,...}气泡:true cancelBubble:false可取消:false组成:false currentTarget:null defaultPrevented:false eventPhase:0 isTrusted:true path:(14)[input.ng-valid.ng-dirty.ng-触摸,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-touched
【解决方案2】:

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

在 TS 中:

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

在 HTML 中:

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
   }

【讨论】:

  • 它可以工作,但它正在选择我不想要的所有按钮。是否只选择一个按钮?当我单击一个单选按钮时,它会选择所有类别。我只想选择 1 个类别。类别是唯一的,因为只有一个类别没有重复。现在有了你的答案,它正在选择我所有的单选按钮。
  • 这意味着你的模型有问题。我可能会使用 id 来保存我的价值。所以 bind 会变成 {{selectedCategoryId}} 并且 value 会是 {{category.id}}
猜你喜欢
  • 2016-09-13
  • 2019-05-11
  • 2014-12-05
  • 1970-01-01
  • 1970-01-01
  • 2017-02-06
  • 2012-07-18
  • 2016-08-30
相关资源
最近更新 更多