我的数据库中有这个值Rating=7
,我正在获取这个值并存储在editUserDetails={}上。现在我在浏览器中显示5到9个单选按钮,我想根据数据库值选择单选按钮。我的意思是,我想选择带有value = 7
的收音机。我写了这个代码,但它不起作用。问题是什么,我需要说些什么。有人能帮忙吗?
我的Html
<div class="col-md-6" *ngFor="let Rating of rates">
<input type="radio" name="Rating" [value]="Rating" [checked]="radioChange(Rating)">
{{Rating.rating}}
</div>
我的Ts
rates:any=[
{rating:"5"},
{rating:"6"},
{rating:"7"},
{rating:"8"},
{rating:"9"},
]
radioChange(Rating){
var match=false;
if(this.editUserDetails.Rating===Rating){
match=true;
}else{}
this.temp = 0;
return match;
}
强文本
//.ts file
data:string;//gloabal declaration
rates:any=[
{rating:"5"},
{rating:"6"},
{rating:"7"},
{rating:"8"},
{rating:"9"},
]
ngOnInit(){
this.data="7";//your formatt
}
<div class="col-md-6" *ngFor="let Rating of rates">
<input type="radio" name="radiodata" [value]="Rating.rating" [(ngModel)]="data"> {{Rating.rating}}
</div>
代码部分不错,但您将传递给函数radioChange
作为包含和属性的参数和对象:
Rating = {rating: "6"}
因此,当你进行比较时,你使用===,并且比较需要是一个相等的对象,所以this.editUserDetails.Rating需要是:
Rating = {rating: "6"}
如果this.editUserDetails.Rating
的值是字符串形式的单个数字,则需要将比较更改为:
this.editUserDetails.Rating===Rating.rating
你应该这样做-
<div class="col-md-6" *ngFor="let Rating of rates">
<input type="radio" name="Rating"
[value]="Rating"
[checked]="this.editUserDetails.Rating === Rating">
<!-- above line marks your radio button checked -->
[value]="Rating"
(change)="onSelectionChange(entry)" >
{{Rating.rating}}
</div>
如果你真的想-onSelectionChange(entry)
是你的组件中的一个功能,当用户更改选项时,你可以执行任何操作-
onSelectionChange(entry) {
this.selectedEntry = entry;
}
使用内置的双向绑定可能更容易。我的单选按钮看起来更像这样:
<div class="col-md-6" *ngFor="let Rating of rates">
<input type="radio"
name="Rating"
[value]="Rating"
[(ngModel)]="selectedRating">
{{Rating.rating}}
</div>
然后组件看起来是这样的:
selectedRating:any;
rates:any=[
{rating:"5"},
{rating:"6"},
{rating:"7"},
{rating:"8"},
{rating:"9"},
]
然后在ngOnit()
中,检索数据后:
console.log(this.editUserDetails.Rating);
this.selectedRating = this.rates.find(item =>
item.rating === this.editUserDetails.Rating.rating);
这种复杂性是由于您绑定的是对象而不是数字。此代码在数组中查找精确的匹配对象。
如果这些值确实是数字,那么绑定数字可能会更容易。
<div class="col-md-6" *ngFor="let Rating of rates">
<input type="radio"
name="Rating"
[value]="Rating.rating"
[(ngModel)]="selectedRating">
{{Rating.rating}}
</div>
然后在ngOnit()
中,检索数据后:
// Note that this is assigning the numeric value, not the object
console.log(this.editUserDetails.Rating.rating);
this.selectedRating = this.editUserDetails.Rating.rating;