angular - 如何在 Angular 12 中预加载单个复选框?
问题描述
我正在尝试在Angular 12应用程序中预加载一个复选框。我见过一些使用 AngularJS 做类似事情的例子,但它们依赖于已弃用的东西。我怀疑这很简单,但我就是不明白。
在我的app.component.ts
文件中,我有一个布尔值,它在应用程序加载时从 API 调用中更新。我想最初显示该值并允许用户稍后更改它。更改成功地告诉 API 新值。
我认为我需要在启动时执行一些 JS 来更新复选框,但我不确定。无论如何,我找到的所有示例都是 AngularJS,所以也许有更好的方法?
FWIW 这就是我的 html 的样子,尽管它相当明显。
<div class="d-flex justify-content-center">
<button title="clear" (click)="clear()">clear</button>
<button title="refresh" (click)="refresh()">refresh</button>
<label for="quiet">Quiet</label>
<input id="quiet" type="checkbox" (change)="onChange($event)"/>
</div>
解决方案
您可以使用模板驱动的表单(或反应式表单)来完成此操作。
应用程序组件.ts
constructor() { }
checkboxControl: boolean = true; <- default it to what you need it to be initially
在 HTML 中,您需要使用[(ngModel)]
将它们绑定在一起。
<div class="d-flex justify-content-center">
<button title="clear" (click)="clear()">clear</button>
<button title="refresh" (click)="refresh()">refresh</button>
<label for="quiet">Quiet</label>
<input id="quiet" type="checkbox" [(ngModel)]="checkboxControl" (change)="onChange($event)"/>
</div>
现在,当您进行 API 调用时,在您的 TS 文件中,您只需更新或设置 checkboxControl 值。
getValueFromService() {
this.service.getCheckboxValue().subscribe(value => {
this.checkboxControl = value
}
}
推荐阅读
- android - 获取 'E/RecyclerView: 未连接适配器;Kotlin tabbedActivity 中的跳过布局
- laravel - 如何避免重复的数据库记录但针对特定用户?
- google-chrome - 如何为 Chrome/Chromium 的“--enable-features=”标志编写参数
- php - HTTP 服务器获取站点文件夹 macOS Big Sur 11.6
- elasticsearch - python 中的 Lambda 函数,用于将指标从 AWS EC2 发送到 Elasticsearch
- java - 为商店经理 (woocommerce) 启用和禁用订单的“编辑”
- gnuplot - 在 gnuplot 中迭代生成数据块
- typescript - 如何在 TypeScript Nuxt.js 应用程序中自动导入类型?
- java - 任务 ':app:mergeDebugResources' android studio 执行失败
- python - 创建一个 5 x 5 矩阵 NumPy