【发布时间】: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);
}
}
在我的项目中,我使用前两个复选框中的语法将复选框添加到 Angular 表单,方法是添加 ngModel 指令,而不使用双向绑定。我尝试了两种不同的方法来默认选中复选框,但都没有奏效。我只是设法通过在ngModel 上使用两种方式绑定来使其工作,如第三个复选框所示。有没有办法让它在没有双向绑定的情况下工作?
【问题讨论】:
标签: angular checkbox angular-forms angular-ngmodel