首页 > 解决方案 > 在模板驱动的表单中默认选中 Angular 复选框

问题描述

我有一个模板驱动的 Angular 表单,其中包含一个复选框,我希望默认选中它。这是最小化的代码:

app.component.html:

<form #form="ngForm" (ngSubmit)="submit(form.value)">
  <input #cb1 type="checkbox" name="cb1" ngModel checked />
  <input #cb2 type="checkbox" name="cb2" ngModel checked="true" />
  <input #cb3 type="checkbox" name="cb3" [(ngModel)]="value" />
  <button type="submit">Submit</button>
</form>

app.component.ts:

import { Component } from '@angular/core';

@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
})
export class AppComponent {
  value=true;
  submit(x: any) {
    console.log(x);
  }
}

StackBlitz

在我的项目中,我使用前两个复选框中的语法将复选框添加到 Angular 表单,方法是添加ngModel指令,而不使用双向绑定。我尝试了两种不同的方法来默认选中复选框,但都没有奏效。我只设法通过使用两种方式绑定来使其工作ngModel,如第三个复选框所示。有没有办法让它在没有双向绑定的情况下工作?

标签: angularcheckboxangular-formsangular-ngmodel

解决方案


只需删除ngModel- 请参阅StackBlitz

UPD:如果您想在表单上添加该复选框 - 您可以使用[ngModel]="true". StackBlitz更新。


推荐阅读