简体   繁体   English

需要在选中复选框后立即取消选中它。 角度4

[英]need to un-check a checkbox as soon as it is checked. Angular 4

i have an object array with a Boolean property bound to a check box 我有一个对象数组,其布尔属性绑定到一个复选框

plunkr https://plnkr.co/edit/j25nOhYm1MNeJzUJzBBs plunkr https://plnkr.co/edit/j25nOhYm1MNeJzUJzBBs

 this.data =  [{ "name":"Ford", "selected":false},
    { "name":"BMW","selected":false },
    { "name":"Fiat","selected":false }
]

in html i tried ngModel and ngModelChange 在HTML中,我尝试了ngModel和ngModelChange

  <li *ngFor="let item of data;">
    <input class="checkbox binning-checkbox" type="checkbox"  
    (ngModelChange)="select(item)" [(ngModel)]="item.selected">
   {{ item.name}}
  </li>

i have also tried [checked] and (change) 我也尝试过[已检查]和(更改)

  <li *ngFor="let item of data;">
    <input class="checkbox binning-checkbox" type="checkbox"  
    (change)="select(item)" [checked]="item.selected">
   {{ item.name}}
  </li>

also tried 也尝试过

<div>
<li *ngFor="let item of data;">
    <input class="checkbox binning-checkbox" type="checkbox" (change)="select(item)" [(ngModel)]="item.selected"> {{ item.name}}
</li>

updated the plunkr but the event code 更新了插件,但事件代码

 public select(item){
alert(item.selected );
item.selected = false;  }

is unable to "de-select" the checkbox 无法“取消选择”复选框

You don't need to change the object to keep the selected status, change the array to 您无需更改对象即可保持选定状态,只需将数组更改为

this.data =  ["Ford","BMW","Fiat"]

<ul>
  <li *ngFor="let item of data">
    <label>
      <input type="checkbox"
        ng-model="xyx"
        ng-click="toggleItem(item)"
        ng-checked="selectedItems.indexOf(item) > -1"
        ng-required="selectedItems.length == 0" /> 
        {{item}}</label>
  </li>                  
</ul>

toggleItem(item){
    var index = this.selectedItems.indexOf(item);
    if(index == -1) {
      this.selectedItems.push(animal);
    }
    else{
      this.selectedItems.splice(index, 1);
    }
}

See the working demo here 这里查看工作演示

You can 'hack' this with setTimeout , which will just a tinytinty time later set the checkbox to false :) 您可以使用setTimeout来“破解”它,稍后会花费很少的时间将复选框设置为false :)

public select(item){
  setTimeout(() => {
    item.selected = false;
  })
}

in your sample demo, I used the ngModel and ngModelChange version: https://plnkr.co/edit/53Tb6wiXYAlat52VPuwG?p=preview 在您的示例演示中,我使用了ngModelngModelChange版本: https : ngModel ngModelChange = ngModelChange

the solution was to use ngModel with change event along with click event 解决方案是将ngModel与change事件以及click事件一起使用

[(ngModel)]="item.selected" (change)="select(dataItem,$event)" (click)="checkExceed($event,dataItem)"

on the click when total number of attempts are greater than xi simply use 当总尝试次数大于xi时,单击即可

$event.preventDefault();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM