0

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:
          {{uploadEnabled}}</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:
          {{uploadEnabled}}</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.

1 Answer 1

0

Turns out that there is an Angular directive [(ngModel)] that does exactly this:

<span>
  <input type="checkbox" [(ngModel)]="advanced.retrieveStoredMeasurements" [ngModelOptions]="{standalone: true}">
  <label> Automatically retrieve stored measurements</label>
</span>

advanced.retrieveStoredMeasurements is the boolean. I have taken out the class attributes for readability.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.