【发布时间】: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