【发布时间】:2022-02-16 21:37:56
【问题描述】:
我必须在我的表单中创建三个复选框,当我选中/取消选中复选框时,它们的值需要切换为“optin”和“optout”(字符串)。此外,我还需要默认选中所有复选框以获取“optin”值。我想不出任何解决方案,任何帮助都将不胜感激:(因为我对 angular 还很陌生
这是我正在处理的代码
component.html
<form [formGroup]="optOutForm" (ngSubmit)="submitOptFormValue()">
<div class="form-group">
<input type="checkbox" formControlName="optOutFlag1" id="privacy" aria-labelledby="check1">
<label for="privacy" id="check1"> Checkbox 1</label><br><br>
<input type="checkbox" formControlName="optOutFlag2" id="security" aria-labelledby="check2">
<label for="security" id="check2"> Checkbox 2</label><br><br>
<input type="checkbox" formControlName="optOutFlag3" id="consent" aria-labelledby="check3">
<label for="consent" id="check3"> Checkbox 3</label><br><br>
<button> Submit Preference </button>
</div>
</form>
component.ts 文件
optOutForm:FormGroup
this.optOutForm=this.fb.group({
optOutFlag1:["optin",Validators.required],
optOutFlag2:["optin",Validators.required],
optOutFlag3:["optin",Validators.required]
});
【问题讨论】:
-
stackoverflow.com/questions/59910767/…。那就是你使用 [ngModel]="if the value of the formControl is 'optin'" and (ngModelChange)="set the value of the formControl if $event==true 'optin' and if is false 'optout'
-
非常感谢@Eliseo 和 frank 的帮助。我已经粘贴了我的有效解决方案:]
标签: javascript angular typescript checkbox angular-forms