将选中的属性赋予循环中的单选按钮

时间:2019-04-16 14:40:17

标签: javascript html angular

我最近陷入困境,当我拥有这样的代码时正在做些事情

<th class="" scope="col" *ngFor="let rating of ratings">
   <div class="form-check form-check-inline">
      <input class="form-check-input" type="radio" [name]="param.paramId" [id]="param.paramId" [value]="rating" (change)="onSelectionChange(rating, param.paramId, coworker.empId)">
   </div>
</th>

如果在此选中单选按钮,则默认情况下会检查循环中的最后一个单选按钮。谁能帮助我,并告诉我如何默认检查第一个单选按钮? 预先感谢。

3 个答案:

答案 0 :(得分:3)

尝试:

<th class="" scope="col" *ngFor="let rating of ratings; let last = last">
   <div class="form-check form-check-inline">
      <input class="form-check-input" type="radio" [name]="param.paramId" [id]="param.paramId" [value]="rating" (change)="onSelectionChange(rating, param.paramId, coworker.empId)" [checked]="last">
   </div>
</th>

<th class="" scope="col" *ngFor="let rating of ratings">
   <div class="form-check form-check-inline">
      <input class="form-check-input" type="radio" [name]="param.paramId" [id]="param.paramId" [value]="rating" (change)="onSelectionChange(rating, param.paramId, coworker.empId)" [checked]="rating.id === 5">
   </div>
</th>

希望它会有所帮助:)

如果这些方法无效,请尝试将属性绑定到[(ngModel)]="entry.id",然后:

ngOnInit() {
    this.entry.id = '5'; // last value
}

答案 1 :(得分:2)

请尝试使用以下代码进行最后检查。

<th class="" scope="col" *ngFor="let rating of ratings; let isLast=last ">
   <div class="form-check form-check-inline">
      <input class="form-check-input" type="radio" 
      [name]="param.paramId" [id]="param.paramId" 
      [value]="rating"
       [checked]="isLast"
       (change)="onSelectionChange(rating, param.paramId, coworker.empId)">
   </div>
</th>

OR

请尝试以下代码进行首次检查。

<th class="" scope="col" *ngFor="let rating of ratings; let isFirst=first">
   <div class="form-check form-check-inline">
      <input class="form-check-input" type="radio" 
      [name]="param.paramId" [id]="param.paramId" 
      [value]="rating"
       [checked]="isFirst"
       (change)="onSelectionChange(rating, param.paramId, coworker.empId)">
   </div>
</th>

答案 2 :(得分:0)

尝试在循环上设置索引,并在索引== 0时添加选中的属性;用于检查第一个无线电,并使用let last = last;否则

<th class="" scope="col" *ngFor="let rating of ratings;let i = index">
   <div class="form-check form-check-inline">
      <input class="form-check-input" type="radio" [name]="param.paramId" [id]="param.paramId" [value]="rating" [checked]="(i === 0) ? 'checked' : ''" (change)="onSelectionChange(rating, param.paramId, coworker.empId)">
   </div>
</th>