Home > Back-end >  Angular how to check a checkbox with [checked] attribute and key value pair?
Angular how to check a checkbox with [checked] attribute and key value pair?

Time:08-09

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 >
    <div >
      <input type="checkbox" 
             id="{{endpoint}}"
             [value]="endpoint"
             [checked]="profileEndpoints.includes(endpoint)"
             name="enabledEndpoints">
      <label  [for]="endpoint">
        {{ endpoint }}
      </label>
    </div>
  </td>
</tr>

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

CodePudding user response:

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 >
    <div >
      <input type="checkbox" 
             id="{{endpoint}}"
             [value]="endpoint"
             [checked]="isChecked(endpoint)"
             name="enabledEndpoints">
      <label  [for]="endpoint">
        {{ endpoint }}
      </label>
    </div>
  </td>
</tr>
  • Related