0

i wanted to check if a value exists in an array and return true if it does and false if it dosent in an angular checkbox input field.

here is the code

 <div style="margin-left: 20px;" *ngFor="let li of permissions;">
            <nz-form-item *ngIf="li.entity === 'Staffs'">
              <nz-form-control style="margin-bottom: -25px;">
                <input type="checkbox" value="{{li.id}}" [checked]="li.id == select" name="staff">{{select}} - {{li.id}}
              </nz-form-control> 
            </nz-form-item>
            
          </div>

select is an array containg id of the selected checkbox values any help is appreciated.

2 Answers 2

2

You probably need to use Array#includes method to perform the check. But it's not a good idea to bind a function to a property like [checked]=select.includes(li.id). In case of default change detection strategy it will get executed for each CD cycle might have a performance impact.

Instead you could run the check in the controller and introduce a new boolean property in the object.e

Controller

ngOnInit() {
  // initialize `permissions` and `select` arrays

  this.permissions = this.permissions.map(permission => ({
    ...permission,
    isChecked: this.select.includes(permission.id)
  });
}

Template

<div style="margin-left: 20px;" *ngFor="let li of permissions;">
  <nz-form-item *ngIf="li.entity === 'Staffs'">
    <nz-form-control style="margin-bottom: -25px;">
      <input type="checkbox" value="{{li.id}}" [checked]="li.isChecked" name="staff">{{select}} - {{li.id}}
    </nz-form-control> 
  </nz-form-item>          
</div>
Sign up to request clarification or add additional context in comments.

3 Comments

i tried it but it is not working i am a beginner on angular so bear with me :)
The code in the controller is only an example. For actual implementation, you'd have to show how the variables permissions and select are initialized.
It is working now but how can i attach the selected values and the other empty check box values if they got selected to the NgModel?
1

Does your select array contain only ids? If so, you can follow @michael's approach or just an add-on approach:

<input type="checkbox" value="{{li.id}}" [checked]="select.indexOf(li.id) > -1" name="staff">

Your checkbox will be checked if select array contains id.

1 Comment

It is working now but how can i attach the selected values and the other empty check box values if they got selected to the NgModel?

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.