I have a template driven Angular form, containing a checkbox, which I want to be checked by default. Here is the minimized code:
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);
}
}
In my project, I add the checkbox to the Angular form using the syntax in the first two checkboxes, by adding the ngModel
directive, without using two-way binding. I tried two different ways to make the checkbox checked by default, but neither worked. I only managed to make it work by using two way binding on ngModel
, as shown in the third checkbox. Is there a way to make it work without two way binding?
CodePudding user response:
Just remove ngModel
- see StackBlitz.
UPD: If you would like to have that checkboxes on the form - you could use [ngModel]="true"
. StackBlitz updated.