1

How do you use [checked] attribute in Angular, alongside key value pair values, that are gotten from backend server? I am receiving data from a response like this:

[{"endpoint":"/profile"},{"endpoint":"/settings"},{"endpoint":"/payments"},{"endpoint":"/login"},{"endpoint":"/accounts"},{"endpoint":"/v2/accounts/*"}]

My checkboxes are dynamically generated. All of the available endpoints are listed from a enabledEndpoints list in the component.ts class, then I want them to be checked, if they are returned in the http response and placed into profileEndpoints object. The object has one variable which is endpoint: string. This is the markup code for it:

<label for="enabledEndpoints">Enabled Endpoints</label>
<tr *ngFor="let endpoint of enabledEndpoints;">
  <td class="pr-4 pl-3">
    <div class="custom-control custom-checkbox">
      <input type="checkbox" class="custom-control-input"
             id="{{endpoint}}"
             [value]="endpoint"
             [checked]="profileEndpoints.includes(endpoint)"
             name="enabledEndpoints">
      <label class="custom-control-label" [for]="endpoint">
        {{ endpoint }}
      </label>
    </div>
  </td>
</tr>

How do I make them checked using the [checked] attribute? I have tried include functions.

0

1 Answer 1

1

Since profileEndpoints is an object with one property endpoint please change the code as below.

in controller add this.

isChecked(endpoint: string): boolean {
    return !!(this.profileEndpoints.find(x => x.endpoint === endpoint))
}

html it will be

<label for="enabledEndpoints">Enabled Endpoints</label>
<tr *ngFor="let endpoint of enabledEndpoints;">
  <td class="pr-4 pl-3">
    <div class="custom-control custom-checkbox">
      <input type="checkbox" class="custom-control-input"
             id="{{endpoint}}"
             [value]="endpoint"
             [checked]="isChecked(endpoint)"
             name="enabledEndpoints">
      <label class="custom-control-label" [for]="endpoint">
        {{ endpoint }}
      </label>
    </div>
  </td>
</tr>
Sign up to request clarification or add additional context in comments.

3 Comments

Does not seem to be working, throws a Parser Error.
@dovexz12323 what is the full error, can I get a stackblitz
Parser Error: Bindings cannot contain assignments at column 26 in [profileEndpoints.find(x => x.endpoint === endpoint)]

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.