【问题标题】:Angular checkbox checked by default in template driven form在模板驱动的表单中默认选中 Angular 复选框
【发布时间】:2021-11-22 15:48:30
【问题描述】:

我有一个模板驱动的 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 上使用两种方式绑定来使其工作,如第三个复选框所示。有没有办法让它在没有双向绑定的情况下工作?

【问题讨论】:

    标签: angular checkbox angular-forms angular-ngmodel


    【解决方案1】:

    只需删除 ngModel - 请参阅 StackBlitz

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

    【讨论】:

    • 好的,但我仍然希望将复选框添加到 ngForm。如果我提交表单(单击按钮),则只会在您的 stackblitz 中打印最后一个复选框的值。
    • 然后,您可以使用[ngModel]="true" - 请参阅StackBlitz
    • 确实解决了。我接受了答案,也许将您的最后评论添加到原始答案中。谢谢:)
    猜你喜欢
    • 2015-03-24
    • 1970-01-01
    • 2018-04-26
    • 1970-01-01
    • 2017-12-18
    • 2019-01-02
    • 2020-04-07
    • 2018-08-15
    • 1970-01-01
    相关资源
    最近更新 更多