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.

1
  • Did you even try to find a solution in your own ? Have you a plunkr with your actual solution ? Commented Feb 17, 2016 at 7:49

4 Answers 4

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;
Sign up to request clarification or add additional context in comments.

1 Comment

Can we use same format for the reactive forms on the angular
6

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>

Comments

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>

Comments

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>

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.