Burst of Ice
Burst of Ice

Reputation: 386

Angular 5 select and unselect a checkbox

Alright I have a terms of service modal which is an ngBootstrap modal and when I press the button to close that button I want the action that closes the modal define wheter the checkbox is checked or not This is the html:

  <ng-template #content let-c="close" let-d="dismiss">
  <div class="modal-header">
  <h4 class="modal-title">Terms of service.</h4>
  <button type="button" class="close" aria-label="Close" (click)="d('Cross 
  click')">
  <span aria-hidden="true">&times;</span>
  </button>
  </div>
  <button type="button" class="btn btn-success" (click)="c('Close click'); 
   setAccepted(true)" >I accept.</button>
  </ng-template>

the link to open the modal and the checkbox

<div class="custom-control custom-checkbox">
            <input *ngIf="accepted" type="checkbox" class="custom-
control-input" id="save-info" required>
            <label class="custom-control-label" for="save-info">I have read 
</label><a href="javascript:void(0)" (click)="open(content)"> 
  the terms of service</a>.
</div>

And under it I have <p>{{accepted}}</p> just for testing

And the typescript

accepted: boolean = false;

constructor(private modalService: NgbModal) {}

open(content) {
 this.modalService.open(content);
}

setAccepted(accepted:boolean){
  this.accepted = accepted;
}

I tried [(ngModel)], *ngIf, ngModel to the accepted boolean from my typescript but nothing seems to work.

Upvotes: 3

Views: 27492

Answers (2)

Basavaraj Bhusani
Basavaraj Bhusani

Reputation: 5673

Use "[checked]" input propery or attribute. Use a Boolean to check on uncheck the checkbox.

In Template:

    <input [checked]="accepted" type="checkbox" class="custom-
control-input" id="save-info" required>

In TS:

accepted: Boolean;
accepted = true;   // Or False

Upvotes: 6

Alex Mackinnon
Alex Mackinnon

Reputation: 299

Hmm, one comment... You have...

 <button type="button" 
 class="btn btn-success" 
 (click)="c('Close click')" 
(click)="setAccepted(true)" >I accept.</button>

Should be

 <button type="button" class="btn btn-success" 
 (click)="c('Close click');setAccepted(true)" >I accept.</button>

At least this is how I do this for a button click, you can not have two separate (click) . I have used this to success on my own personal site.

Upvotes: 0

Related Questions