dovexz12323
dovexz12323

Reputation: 277

Angular how to check a checkbox with [checked] attribute and key value pair?

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.

Upvotes: 1

Views: 1494

Answers (1)

Naren Murali
Naren Murali

Reputation: 57531

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>

Upvotes: 1

Related Questions