angular - 在模板驱动的表单中默认选中 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);
}
}
在我的项目中,我使用前两个复选框中的语法将复选框添加到 Angular 表单,方法是添加ngModel
指令,而不使用双向绑定。我尝试了两种不同的方法来默认选中复选框,但都没有奏效。我只设法通过使用两种方式绑定来使其工作ngModel
,如第三个复选框所示。有没有办法让它在没有双向绑定的情况下工作?
解决方案
只需删除ngModel
- 请参阅StackBlitz。
UPD:如果您想在表单上添加该复选框 - 您可以使用[ngModel]="true"
. StackBlitz更新。
推荐阅读
- mdx - MDX中Set vs Tuple的解释
- hex - MIPS 中的十六进制转十进制。我从 $s3 得到了非常奇怪和负面的输出,真的可以使用一些帮助,因为我完全没有想法
- java - LWJGL 上 glUniform1fv() 导致的 JVM 崩溃
- c# - 在 C# 中循环数组或列表并使用 MongoDB 执行更新
- amazon-web-services - 如何在没有特定标签和值的情况下自动停止 EC2 实例
- asp.net - ASP.NET CORE 3.1 身份验证 Cookie,但仅存储用户名
- dataframe - 在字符串列上连接两个 DataFrame 但忽略重音符号/变音符号
- php - PHP不删除MYSQL数据库行
- flutter - 当我尝试从 Visual Studio Code 运行 Flutter 时出现这些错误
- python - Python 键盘模块,等待用户