首页 > 解决方案 > 如何在 Angular 中的复选框上设置默认值?

问题描述

我有以下代码:

<input type="checkbox" [(ngModel)]="i.checkt" [ngModelOptions]= 
{standalone:true} (change)="recovery(i.checkt,i.TherapeuticArea)"> 
{{i.TherapeuticArea}}

我面临的问题是,使用standalone:true 默认选中每个复选框,当standalone 为false 时,复选框不起作用。有没有办法在为用户提供完整功能的同时将复选框值设置为未选中?

标签: htmlangularcheckbox

解决方案


您需要checked在输入上设置属性,如下所示:

<input type="checkbox" [(ngModel)]="i.checkt" [ngModelOptions]={standalone:true} 
(change)="recovery(i.checkt,i.TherapeuticArea)" [checked]="i.checkt"> 

但我会推荐@Florian 的评论,即使用 FormControl 来管理来自 UI 的输入。在我看来,它将为您节省大量时间并使其更易于维护。


推荐阅读