如何根据值检查复选框
How to check checkbox base on value
我的想法
我收到值 "Yes" 和 "No" 。如果我收到“是”,我想选中复选框,当我收到“否”时,我想取消选中复选框
收到数据
{
"expires_in": 0,
"data": [
{
"id": 0,
"patientId": 2143,
"substanceAbuseAlcohol": "No",
"substanceAbuseMarijuana": "Yes",
}]}
我试过的代码
此代码始终选中复选框,即使我收到是或否。我只想检查从 Api
收到的数据是否是
<section class="pleft ptop">
<mat-checkbox color="primary"
(change)="patientPastHistoryForm.get('substanceAbuseAlcohol').setValue(
$event.checked ? 'Yes' : 'No')"
checked="patientPastHistoryForm.get('substanceAbuseAlcohol')==='Yes'"
>Alcohol</mat-checkbox><br>
<mat-checkbox (change)="patientPastHistoryForm.get('substanceAbuseMarijuana').setValue(
$event.checked ? 'Yes' : 'No')"
checked="patientPastHistoryForm.get('substanceAbuseMarijuana')==='Yes'" color="primary" >Marijuana</mat-checkbox><br>
<mat-form-field>
<mat-label>Other</mat-label>
<input type="other" matInput formControlName="substanceAbuseOther"
placeholder="">
</mat-form-field>
</section>
形式
this.patientPastHistoryForm = new FormGroup({
patientId: new FormControl(this.clientId),
substanceAbuseAlcohol: new FormControl('No'),
substanceAbuseMarijuana: new FormControl('No'),
根据 Angular Material 文档中的 this example,我建议您使用 [(ngModel)]
来控制复选框的状态。
我创建了一个 Stackblitz 演示来向您展示如何使用它:demo
在您的情况下,当您收到数据时,请用您想要的值更新 class 中选中的变量,假设 'Yes'
是 true
和 'No'
是 false
,您的复选框将被更新。
我的想法 我收到值 "Yes" 和 "No" 。如果我收到“是”,我想选中复选框,当我收到“否”时,我想取消选中复选框
收到数据
{
"expires_in": 0,
"data": [
{
"id": 0,
"patientId": 2143,
"substanceAbuseAlcohol": "No",
"substanceAbuseMarijuana": "Yes",
}]}
我试过的代码 此代码始终选中复选框,即使我收到是或否。我只想检查从 Api
收到的数据是否是 <section class="pleft ptop">
<mat-checkbox color="primary"
(change)="patientPastHistoryForm.get('substanceAbuseAlcohol').setValue(
$event.checked ? 'Yes' : 'No')"
checked="patientPastHistoryForm.get('substanceAbuseAlcohol')==='Yes'"
>Alcohol</mat-checkbox><br>
<mat-checkbox (change)="patientPastHistoryForm.get('substanceAbuseMarijuana').setValue(
$event.checked ? 'Yes' : 'No')"
checked="patientPastHistoryForm.get('substanceAbuseMarijuana')==='Yes'" color="primary" >Marijuana</mat-checkbox><br>
<mat-form-field>
<mat-label>Other</mat-label>
<input type="other" matInput formControlName="substanceAbuseOther"
placeholder="">
</mat-form-field>
</section>
形式
this.patientPastHistoryForm = new FormGroup({
patientId: new FormControl(this.clientId),
substanceAbuseAlcohol: new FormControl('No'),
substanceAbuseMarijuana: new FormControl('No'),
根据 Angular Material 文档中的 this example,我建议您使用 [(ngModel)]
来控制复选框的状态。
我创建了一个 Stackblitz 演示来向您展示如何使用它:demo
在您的情况下,当您收到数据时,请用您想要的值更新 class 中选中的变量,假设 'Yes'
是 true
和 'No'
是 false
,您的复选框将被更新。