I have a simple boolean in my angular 16 ts component uploadEnabled
. What I want is the checkbox to be checked if uploadEnabled
is true and vice versa. When I click on the checkbox I want uploadEnabled
to toggle accordingly with the state of the checkbox. I have a label element showing the current state of uploadEnabled
.
The following code does what I want but it is clearly clumsy as I am using two input elements and *ngIf
to either have the checked
attribute present or absent. (I have removed class
attributes for readability.)
<form >
<input type="checkbox" (click)="uploadEnabled = !uploadEnabled" *ngIf="!uploadEnabled" />
<input type="checkbox" (click)="uploadEnabled = !uploadEnabled" *ngIf="uploadEnabled" checked />
<label >Allow PHG to perform FHIR/PCD01 uploads:
</label>
</form>
The variant below does half the job. The checkbox will be checked or unchecked when first viewed depending upon the boolean, but clicking on the checkbox sets the checkbox to checked if not checked otherwise it just remains checked. The boolean value, however, toggles as desired:
<input type="checkbox"
(click)="uploadEnabled = !uploadEnabled" [checked] = "uploadEnabled" />
<label >Allow PHG to perform FHIR/PCD01 uploads:
</label>
I have tried other variants with '[(ngModel)]' and '(change)' but either I have gotten compile errors (I am using Angular 16 with strict mode) or I could not get consistency between the check box state and the variable. In the end all I am trying to do it eliminate the checked
attribute when uploadEnabled
is false and to have it present when uploadEnabled
is true.
Aucun commentaire:
Enregistrer un commentaire