0

I'm trying to connect a checkbox's boolean value to a table's class.

so, if checkbox is checked => enable dark mode.

I've tried the following:

<link href="https://stackpath.bootstrapcdn.com/bootstrap/4.2.1/css/bootstrap.min.css" rel="stylesheet" />
<table class="table table-striped" [ngClass]="{'table-dark': darkMode == 'true'}">
  <thead class="thead-light">
    <tr>
      <th scope="col">1</th>
      <th scope="col">2</th>
      <th scope="col">3</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td>1</td>
      <td>2</td>
      <td>3</td>
    </tr>
  </tbody>
</table>

<div class="custom-control custom-switch">
  <input type="checkbox" class="custom-control-input" [checked]="darkMode" ([ngModel])="darkMode=(darkMode ? false : true)" id="customSwitch">
  <label class="custom-control-label" for="customSwitch">Toggle Dark Mode</label>
</div>

How can i tie a boolean value from a checkbox to an inline-angular variable and apply a css-class?

Joel
  • 5,732
  • 4
  • 37
  • 65
  • Possible duplicate of [Bootstrap 4 dark & light mode switch](https://stackoverflow.com/questions/53077314/bootstrap-4-dark-light-mode-switch) – Akber Iqbal Feb 04 '19 at 09:59
  • @AkberIqbal Before you mark something as `possible duplicate`. Please read what the question is really about... – Joel Feb 04 '19 at 10:04

1 Answers1

0

Use ngModel Directive then place the template ref in the input and assign to ngModel Directive and use that template ref to bind the class dynamically

<table class="table table-striped" [ngClass]="{'table-dark': ref.value == true}">
  <thead class="thead-light">
    <tr>
      <th scope="col">1</th>
      <th scope="col">2</th>
      <th scope="col">3</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td>1</td>
      <td>2</td>
      <td>3</td>
    </tr>
  </tbody>
</table>

<div class="custom-control custom-switch">
  <input type="checkbox" class="custom-control-input" #ref="ngModel" ngModel id="customSwitch" name="chec">  
  <label class="custom-control-label" for="customSwitch">Toggle Dark Mode</label>
</div>

https://stackblitz.com/edit/angular-nkthpk

For More Info about Angular form:https://angular.io/guide/forms

Chellappan வ
  • 23,645
  • 3
  • 29
  • 60
  • Is it possible to create an inline-variable and thereby eliminating the forced use of a variable in the controller? This was previously possible in aJS by doing `(darkMode=(darkMode ? false : true))` this would create an inline variable and assign a boolean value to it – Joel Feb 04 '19 at 09:56
  • Template variable will point to the current element Object where the variable was hosted. Example I have place the template variable #ref in the input element. now the ref will give the access to the current input element native properties like value and methods. – Chellappan வ Feb 04 '19 at 10:08