【问题标题】:dynamic list of radiobuttons in angular角度单选按钮的动态列表
【发布时间】:2019-04-01 04:14:06
【问题描述】:

我有一个不属于表单的单选按钮列表。我想根据一个值将其中一个设置为 true。

然后,当点击另一个时,所有其他都设置为 false,除了点击的那个。

单选按钮列表是动态的,由ngFor 生成,

我有类似的东西

<div *ngFor='let item of array;let i = index'>                    
   <input type="radio" [checked]=false (click)='radioChecked(item.id,i)' > <input type="text" value='{{item.name}}' >  <button type="button" >save</button>                    
 </div>  

ngOnInit() {  
  this.myService.getNumber(id).subscribe((data) =>{  
  //when the page loads, set one of radiobuttons to true
  //somehow get the id and set to true, no standard is, since dynamic list
  radioId.value = true;
  })
}

radioChecked(id, i){
  //turn all the others to false, except this one
}

由于这不是表格,也没有标准行,所以我可以有一个 id,我该怎么做?我使用角度 6

谢谢

【问题讨论】:

    标签: angular radio-button angular6


    【解决方案1】:

    selected 属性应该是数组中 item 对象的一部分。

    模板:

        <div *ngFor='let item of array;let i = index'>                    
           <input type="radio" [checked]="item.selected" (change)='radioChecked(item.id,i)' > 
            <input type="text" value='{{item.name}}'/>  
            <button type="button">save</button>                    
         </div> 
    

    组件:

     radioChecked(id, i){
      array.forEach(item=>{
        if(item.id !== id){ 
           item.selected = false;
        }else{
           item.selected = true;
        } 
      })
    }
    

    【讨论】:

    • 谢谢苏雷什。除了将item.selected 放在对象中之外,我也没有看到任何其他解决方案
    【解决方案2】:

    其实正确答案是使用(click)而不是(change)

    【讨论】:

      猜你喜欢
      • 2018-09-17
      • 2023-04-10
      • 1970-01-01
      • 2019-12-16
      • 1970-01-01
      • 2014-09-20
      • 1970-01-01
      • 2021-04-07
      • 1970-01-01
      相关资源
      最近更新 更多