【问题标题】:uncheck a checkbox which is checked and freezed with a condition in Angular 5取消选中一个复选框,该复选框在 Angular 5 中被选中并冻结了一个条件
【发布时间】:2020-02-25 08:13:51
【问题描述】:

我有一个迭代 JSON 值的表,我在第一列有复选框

要求:当5个复选框被选中时,用户应该不能选择第6个复选框,但他可以取消选择5个复选框中的任何一个

当前场景:当用户选择 5 个复选框时,我可以冻结复选框,但不允许我取消选中选中的复选框

<checkbox [forbidden]="isFull() && !Selected" [ngModel]="Selected" (ngModelChange)="Change(Result, $event)"></checkbox>

复选框是我代码库中的自定义组件

isFull() {
    return someService.Slots()===0; // availableSlots returns 5
}

Change(Result, $event){
    // some code irrelevant to the checkbox logic
    // Result holds the JSON value for iterating row
}

请提供工作人员或任何在线编辑器以便更好地理解

提前致谢

【问题讨论】:

标签: javascript angular checkbox html-table


【解决方案1】:

希望对您有所帮助!,您可以根据需要对其进行优化和修改。

工作样本plunker

模板文件:

 template: `
          <ul>
            <ng-container>
                <li *ngFor="let item of list">
                <input 
                    type="checkbox" 
                    value="{{item.value}}"
                    [disabled]="item.disabled"
                     (change)="onCheckboxChange($event, item)"
                    /> 
                    {{item.label}}<br>
                </li>
            </ng-container>
          </ul>
         <pre> {{checkedList | json}} </pre>
        `

类文件

 export class App {
        name: string;
        checkedList: any = [];
        list: any = [
            {'label': 'A', 'value': 'a', 'disabled': false},
            {'label': 'B', 'value': 'b', 'disabled': false},
            {'label': 'C', 'value': 'c', 'disabled': false},
            {'label': 'D', 'value': 'd', 'disabled': false},
            {'label': 'E', 'value': 'e', 'disabled': false},
            {'label': 'F', 'value': 'f', 'disabled': false},
            {'label': 'G', 'value': 'g', 'disabled': false}
        ];
        constructor() {

        }

        onCheckboxChange(e, item) {

            if(e.target.checked) {
                this.checkedList.push(item);
            } else {
                let index = this.checkedList.findIndex(obj => item.value === obj.value);
                if(index > -1) {
                    this.checkedList.splice(index,1);
                }
            }

            if(this.checkedList.length > 4) {  // *change available slots*
                let unCheckedList = this.list.filter((obj) => {
                   let isCheck = this.checkedList.find((item) => {
                        return item.value === obj.value
                    }); 
                    obj.disabled = !isCheck ? true : false;
                    return !isCheck;
                });
            } else {
               this.list.map((obj)=>{
                   obj.disabled = false;
               });
            }
        }
    }

【讨论】:

    【解决方案2】:

    不应该是“isFull() && !Selected”吗?因为你想冻结未选中的,但仍然可以取消选中选中的。

    【讨论】:

    • 这是我的一个错字,即使在改变之后也没有任何想法?我更正了问题
    【解决方案3】:

    更新

    试试这个:

    import { Component } from "@angular/core";
    import { list } from './list';
    
    @Component({
      selector: "my-app",
      templateUrl: "./app.component.html",
      styleUrls: ["./app.component.css"]
    })
    export class AppComponent {
      list: Array<any>;
      checked = [];
      shouldCheckboxesBeDisabled = false;
    
      ngOnInit() {
        this.list = list;
        this.recheckDisablingStatus();
      }
    
      recheckDisablingStatus() {
        this.shouldCheckboxesBeDisabled = this.list.filter(item => item.checked).length >= 5;
      }
    
      uncheckIfAlreadyChecked(itemIndex) {
        const isChecked = this.list[itemIndex].checked;
        this.list[itemIndex].checked = isChecked ? false : isChecked;
        this.recheckDisablingStatus();
      }
    }
    

    在模板中:

    <table border="1">
      <thead>
        <td>ID</td>
        <td>Name</td>
        <td>Checked</td>
        <td>Uncheck if Already Checked</td>
      </thead>
      <tbody>
        <tr *ngFor="let item of list; let i = index">
          <td>{{ item.id }}</td>
          <td>{{ item.name }}</td>
          <td>
            <input 
              [disabled]="shouldCheckboxesBeDisabled && !list[i].checked"
              type="checkbox" 
              [(ngModel)]="list[i].checked"
              (change)="recheckDisablingStatus()">
          </td>
          <td><button (click)="uncheckIfAlreadyChecked(i)">Uncheck If Checked</button></td>
        </tr>
      </tbody>
    </table>
    

    这里有一个Working Sample StackBlitz 供您参考。

    原始答案

    试试这个:

    <table border="1">
      <thead>
        <td>ID</td>
        <td>Name</td>
        <td>Checked</td>
      </thead>
      <tbody>
        <tr *ngFor="let item of list$ | async; let i = index">
          <td>{{ item.id }}</td>
          <td>{{ item.name }}</td>
          <td>
            <input 
              [disabled]="shouldCheckboxesBeDisabled && checked.indexOf(item.id) < 0"
              type="checkbox" 
              (change)="onCheckBoxChange(item.id, $event.target.checked)">
          </td>
        </tr>
      </tbody>
    </table>
    

    在你的组件中:

    import { Component } from "@angular/core";
    import { Observable, of } from "rxjs";
    import { HttpClient } from "@angular/common/http";
    
    @Component({
      selector: "my-app",
      templateUrl: "./app.component.html",
      styleUrls: ["./app.component.css"]
    })
    export class AppComponent {
      list$: Observable<Array<any>>;
      checked = [];
      shouldCheckboxesBeDisabled = false;
    
      constructor(private http: HttpClient) {}
    
      ngOnInit() {
        // this.list$ = this.http.get<Array<any>>('/assets/data.json');
        this.list$ = of([
          {
            id: 1,
            name: "Name 1",
            checked: false
          },
          {
            id: 2,
            name: "Name 2",
            checked: true
          },
          {
            id: 3,
            name: "Name 3",
            checked: false
          },
          {
            id: 4,
            name: "Name 4",
            checked: true
          },
          {
            id: 5,
            name: "Name 5",
            checked: false
          },
          {
            id: 6,
            name: "Name 6",
            checked: true
          },
          {
            id: 7,
            name: "Name 7",
            checked: false
          },
          {
            id: 8,
            name: "Name 8",
            checked: true
          },
          {
            id: 9,
            name: "Name 9",
            checked: false
          },
          {
            id: 10,
            name: "Name 10",
            checked: true
          }
        ]);
      }
    
      onCheckBoxChange(itemId, checked) {
        if(checked) {
          this.checked.push(itemId);
        } else {
          const itemIndexToRemove = this.checked.indexOf(itemId);
          this.checked.splice(itemIndexToRemove, 1);
        }
        this.shouldCheckboxesBeDisabled = this.checked.length >= 5;
      }
    }
    

    这里有一个Working Sample StackBlitz 供您参考。

    【讨论】:

    • 感谢您的帮助,您能再做一件事吗?如果我传递 id 值,它应该检查复选框是否被选中,如果选中则取消选中,非常感谢
    • 您好,很抱歉,我不太明白您上面评论的意思。您的意思是复选框的选中状态将出现在数据中,我必须首先使用该选中值加载它吗?我的意思是,假设名称 3 项的 checked 状态为真,您希望选中表中的复选框 3。你是这个意思吗?
    • 来自 TS 如果我有“id”列值,我需要一个逻辑来检查相应的复选框是否已被选中,如果选中则取消选中相同
    • 如果不检查会发生什么?让它检查?还是什么都不做?
    • 如果未选中则不执行任何操作
    猜你喜欢
    • 2023-03-13
    • 1970-01-01
    • 2018-04-15
    • 2021-12-23
    • 2018-08-29
    • 2023-04-05
    • 2015-06-19
    • 1970-01-01
    相关资源
    最近更新 更多