10

I've got a checkbox and what I'm trying to achieve is to hide the div when the checkbox is checked and show when it is unchecked in Angular 2.0 beta.

I know how to do this in angular 1.2 with this code

<label>
     <input type="checkbox" ng-model="showhidepregnant"/> Pregnant
</label>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;

Code on the div

<div class="col-md-4 divhidetxtdpatient" ng-hide="showhidemasked">
      <input class="form-control" tabindex="1" id="id_field_specialist" ng-model="id_field_specialist" type="text" ng-blur="savespecialist()" placeholder="maskable"/>
</div>

Thanks in advance.

Shashank Agrawal
  • 25,161
  • 11
  • 89
  • 121
Kevin Lopez
  • 313
  • 3
  • 4
  • 14

4 Answers4

11

Provide [(ngModel)] for your checkbox and use the same ngModel using *ngIf for your div tag. See the below code sample.

<label>
   <input type="checkbox" [(ngModel)]="showhidepregnant"/> Pregnant
</label>

Then use the same mode:

<div class="col-md-4 divhidetxtdpatient" *ngIf="showhidepregnant">

NB: Please declare the model in your .ts file also:

showhidepregnant: boolean;
A J
  • 3,970
  • 14
  • 38
  • 53
Renju
  • 119
  • 1
  • 5
5

You can also use the #variable syntax from Angular. checked (register.checked) is the property of the input element which returns the checked state of the element.

Note: the event-binding (checked) is needed to trigger the check for changes if the user has checked/unchecked the checkbox:

<div *ngIf="register.checked">
  <h1>Hallo</h1>
</div>
<label><input (change)="register" #register type="checkbox"> Register</label>
Mert
  • 1,333
  • 1
  • 12
  • 15
3

Basically you need to use [hidden] property binding for showing and hiding HTML.

And then use [(ngModel)] for two way binding in Angular2 & use (eventName) to have event bounded to DOM.

Markup

<label>
   <input type="checkbox" [(ngModel)]="showhidepregnant"/> Pregnant
</label>

<div class="col-md-4 divhidetxtdpatient" [hidden]="showhidemasked">
   <input class="form-control" tabindex="1" id="id_field_specialist" 
   [(ngModel)]="id_field_specialist" type="text" 
   (blur)="savespecialist()" placeholder="maskable"/>
</div>
Community
  • 1
  • 1
Pankaj Parkar
  • 134,766
  • 23
  • 234
  • 299
1

you can check whether checkbox is checked or not by applying (change) hook on the basis of checkbox property try to hide or show div,

here is working plnkr for same:

http://plnkr.co/edit/mIj619FncOpfdwrR0KeG?p=preview

.ts file code:

checked(value){
    if(document.getElementById('abc').checked==true){
      this.shown= true
    }
    else if(document.getElementById('abc').checked==false)
      this.shown= false;
  }

.html

<input type='checkbox' id= 'abc' (change)="checked('abc')">

<div *ngIf='shown'>
  Hello CheckBox
</div>
Pardeep Jain
  • 84,110
  • 37
  • 165
  • 215