【问题标题】:Bootstrap 4 - switching between light and darkmode using checkboxBootstrap 4 - 使用复选框在明暗模式之间切换
【发布时间】:2019-02-04 09:47:06
【问题描述】:

我正在尝试将复选框的布尔值连接到表的类。

所以,如果选中复选框 => 启用暗模式。

我尝试了以下方法:

<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>

如何将复选框中的布尔值绑定到内联角度变量并应用 css 类?

【问题讨论】:

标签: angular bootstrap-4


【解决方案1】:

使用 ngModel 指令然后将模板 ref 放入输入中并分配给 ngModel 指令并使用该模板 ref 动态绑定类

<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

有关 Angular 表单的更多信息:https://angular.io/guide/forms

【讨论】:

  • 是否可以创建一个内联变量,从而消除在控制器中强制使用变量?以前在 aJS 中可以通过 (darkMode=(darkMode ? false : true)) 执行此操作,这将创建一个内联变量并为其分配一个布尔值
  • 模板变量将指向托管变量的当前元素对象。示例 我已将模板变量 #ref 放在输入元素中。现在 ref 将允许访问当前输入元素的原生属性,如值和方法。
猜你喜欢
  • 2021-05-30
  • 2021-09-08
  • 2020-10-01
  • 2020-12-05
  • 2020-04-15
  • 2020-09-12
  • 1970-01-01
  • 2020-08-24
  • 2021-09-12
相关资源
最近更新 更多