【问题标题】:How to bind ngmodel inside each item in for loop angular 8?如何在for循环角度8中的每个项目内绑定ngmodel?
【发布时间】:2021-02-07 01:47:27
【问题描述】:

我想取消选择单选按钮,但是在搜索了很多之后..我没有找到答案。所以我选择使复选框作为单选按钮工作的方式(仅单选)。它工作得很好,但是当我无法将 ngmodel 绑定到复选框时。 我想要这样的复选框

  • 项目1 ID 姓名
  • 项目2 ID 姓名
  • 项目 3 ID 姓名

我需要从项目列表中选择一个复选框项目(ID 和名称中的一个)。

【问题讨论】:

    标签: checkbox angular8 ngmodel


    【解决方案1】:

    请使用 [(ngModel)] 检查此代码。

    HTML

    <div *ngFor = "let item of data ; let i = index">
      <input type="checkbox" name="cb1" [(ngModel)]="item.IsSelected" (change)="toggleSelection(i)" /> {{item.name}}
    </div>
    

    组件

    import { Component } from '@angular/core';
    
    @Component({
      selector: 'my-app',
      templateUrl: './app.component.html',
      styleUrls: [ './app.component.css' ]
    })
    export class AppComponent  {
      data : any = [
        {'id': 1 , 'name': 'item-1'},
        {'id': 2 , 'name': 'item-2'},
        {'id': 3 , 'name': 'item-3'},
        {'id': 4 , 'name': 'item-4'}
      ];
    
     toggleSelection(i){
       this.data.forEach((item, index) => {
         if(index != i){
           this.data[index].IsSelected = false
         }
       })
      }
    
      getSelectedItem(){
        const selectedItem = this.data.filter( (item) => item.IsSelected );
        console.log("selected option is ", selectedItem);
      }
    
    }
    

    【讨论】:

      猜你喜欢
      • 2018-06-12
      • 2021-08-30
      • 2017-09-06
      • 1970-01-01
      • 1970-01-01
      • 2019-04-11
      • 2018-11-23
      • 1970-01-01
      • 2017-05-29
      相关资源
      最近更新 更多