【问题标题】:In Angular how to load the radio button value when we click on Edit option在Angular中,当我们单击编辑选项时如何加载单选按钮值
【发布时间】:2018-10-22 10:49:12
【问题描述】:

当我点击编辑表单按钮时,如何在 Angular 中加载单选按钮值。

这是我的用户界面。

当我点击保存时,数据被插入到数据表中。但是当我点击编辑按钮时,表单没有加载单选按钮值,当我点击更新按钮时,数据应该会被影响到数据表中。

app.component.html

<div class="col-sm-10"> 
     <input type="radio" name="gender" [(ngModel)]="model.gender" value="male" checked> Male                         
     <input type="radio" name="gender" [(ngModel)]="model.gender" value="female"> Female<br>
 </div>
<button type="submit" class="btn btn-default" (click)="addEmployee()">Save</button>
<a class="btn btn-success" (click)="editEmployee(i)">Edit</a>
<button type="submit" class="btn btn-default" (click)="updateEmployee()">Update</button>

这是我的 app.component.ts

myValue;
  editEmployee(k){
    this.model2.name = this.employees[k].name;
    this.model2.DOB=this.employees[k].DOB;
    this.model2.mob = this.employees[k].mob;
    this.myValue = k;
  }

  updateEmployee(){
    let k= this.myValue;
    for(let i=0; i<this.employees.length;i++){
      if(i==k){
        this.employees[i]= this.model2;
        this.model2 = {};   
        this.msg = "Record is successfully updated..... ";
      }
    }  
  }

【问题讨论】:

标签: javascript angular


【解决方案1】:

单选按钮的数据绑定与 value 属性一起使用,并且不依赖于 checked 属性。所以如果你设置例如“男性”在您的模型中作为默认值,它将在模板中被选中。

所以要加载性别,只需访问“男性”或“女性”的 model.gender。每当您单击其中一个单选按钮时,都应该为您更新 Angulars 双向数据,因为它会自动更新您的模型。

https://stackblitz.com/edit/angular-eferut?file=src%2Fapp%2Fapp.component.html

【讨论】:

    【解决方案2】:

    您的 html 看起来不错,您需要在 ts 文件中进行更改。基本上名称 model12 是错误的,您不需要单独分配单个值。

    你的代码看起来像 -

      model;
      selectedIndex;
    
      editEmployee(k){
        this.selectedIndex = k;
        this.model = Object.assign({},this.employees[k]);
      }
    
      updateEmployee(){
    
        if(this.employees[this.selectedIndex]){
          Object.assign(this.employees[this.selectedIndex], this.model);
           this.msg = "Record is successfully updated..... ";
        }else{
          this.employees.push(Object.assign({}, this.model));
          this.msg = "Record is successfully added..... ";
        }
      }
    

    【讨论】:

    • 请查看我的帖子,我已更新。说真的,我不知道如何执行。
    猜你喜欢
    • 1970-01-01
    • 2021-11-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-12-14
    • 1970-01-01
    • 2013-02-27
    相关资源
    最近更新 更多