首页 > 解决方案 > 如何在 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> 

标签: angular

解决方案


您可以使用模板驱动的表单(或反应式表单)来完成此操作。

应用程序组件.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
  }
}

推荐阅读