如何为单选按钮“选中”属性动态分配true或false?

时间:2019-06-22 17:07:21

标签: html angular

我正在遍历数据数组,如下所示:

<div class="row mt-2">
    <div class="col d-flex justify-content-center">
        <input *ngFor="let radio of template.selection" 
            type="radio" class="mr-1" 
            name="{{radio.name}}" 
            checked="{{radio.checked}}">        
    </div>  
</div>

我想根据下面显示的选择数组的“ checked”字段为单选按钮的“ checked”属性动态分配true或false,但这不起作用。

数据:

selection: [
   {name: 'none', checked:true},
   {name: 'full', checked:false},
   {name: 'right', checked:false},
   {name: 'left', checked:false},                    
]

2 个答案:

答案 0 :(得分:1)

首先,您的数据应为:

selection =  [
   {name: 'none', checked:true},
   {name: 'full', checked:false},
   {name: 'right', checked:false},
   {name: 'left', checked:false},                    
]

使用[checked]代替checked

<div class="row mt-2">
    <div class="col d-flex justify-content-center">
        <input *ngFor="let radio of selection" 
            type="radio" class="mr-1" 
            name="{{radio.name}}" 
            [checked]="radio.checked">        
    </div>  
</div> 

正在工作的Stackblitz demo

答案 1 :(得分:0)

如果使用单选按钮,请考虑以下设置。

  selection = [
    { name: 'none' },
    { name: 'full' },
    { name: 'right' },
    { name: 'left' },
  ]

  selectedValue = 'full';

html:

<ng-container *ngFor="let r of selection">
  <input  type="radio" name="some" [value]="r.name" [(ngModel)]="selectedValue">{{r.name}}
</ng-container>

<pre>
  {{ selectedValue }}
</pre>

Stackblitz