Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to uncheck a checkbox in angular2

I have code in the HTML file that looks like this

 <tr *ngFor="#tradeSource of tradeSources">
     <td>
         <label>
         <input type="checkbox" ngControl="tradeSource"    [(ngModel)]="tradeSource['checked']"/>
         </label>
     </td>           
     <td>{{tradeSource.blah}}</td>
     <td>{{tradeSource.blah}}</td>
     <td>{{tradeSource.blah}}</td>
</tr>

A user can check the check box then click a "Process" button that will run some code, after this code has run I would like to uncheck this checkbox. Ive tried code like

this.tradeSources[i]['checked'] = false

But this isnt working

like image 713
Mufasatheking Avatar asked Apr 20 '16 14:04

Mufasatheking


People also ask

How do I uncheck a checkbox in TypeScript?

How do I uncheck a checkbox in TypeScript? If you need to uncheck the checkbox, set its checked property to false . To set a checkbox to checked/unchecked in TypeScript: Select the checkbox element.

How do you check checkbox is checked or unchecked in angular?

The ng-checked Directive in AngularJS is used to read the checked or unchecked state of the checkbox or radio button to true or false. If the expression inside the ng-checked attribute returns true then the checkbox/radio button will be checked otherwise it will be unchecked.


2 Answers

The code you should rather try is:

this.tradeSources[i]['checked'] = false

Edit

I think that your problem is because you have the same name for each control of checkboxes:

<input type="checkbox" ngControl="tradeSource"  
       [(ngModel)]="tradeSource.checked"/>

If you remove the ngControl attribute, it works:

<input type="checkbox" [(ngModel)]="tradeSource.checked"/>

See this plunkr: https://plnkr.co/edit/FdPHpOTSySkg2gLWjo7a?p=preview.

If you really want an ngControl you could define it this way:

<tr *ngFor="#tradeSource of tradeSources;#i=index">
  <td>
    <label>
      <input type="checkbox" [ngControl]="'trade'+i" 
             [(ngModel)]="tradeSource.checked"/>
    </label>
  </td>           
  (...)
</tr>
like image 141
Thierry Templier Avatar answered Oct 09 '22 03:10

Thierry Templier


I believe the reason this is not working, and which should probably also throw an error in your console, is the usage of unbinded ngControl. It should be enough to just do:

<input type="checkbox" [(ngModel)]="tradeSource['checked']">
like image 20
Poul Kruijt Avatar answered Oct 09 '22 05:10

Poul Kruijt