Angular 复选框在模板驱动形式中默认选中
Angular checkbox checked by default in template driven form
我有一个模板驱动的 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 已更新。
我有一个模板驱动的 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 已更新。