mercredi 14 juin 2017

angular 2 - initial state of the list of checkboxes

I'm new to Angular :) I'm trying to set the initial state of checkboxes. I have a post and categories, some of them already assigned to that post. When I navigate to the post edit page there's a list of all categories, which I can select / deselect. What I try to achieve is that on init certain checkboxes (categories already assigned to the post) are checked. Here's what I have:

//document-edit.component.html
<div *ngFor="let category of categories">
    <div class="checkbox">
        <label>
            <input type="checkbox"
                   [checked]="checkIfCategoryAssigned(category.documents, document.id)"
                   (change)="onChange(category.id, category.name, $event.target.checked)"> 
        </label>
    </div>
</div>

// document-edit.component.ts
checkIfCategoryAssigned(categoryDocuments, documentId) {
    for (let document of categoryDocuments) {
        if (document.id === documentId) {
            console.log('true');
            return true;
        }
    }
}

It seems to be working, but the problem is that the function is called on every mouse move! I've read that I should use an Observable but I have no idea how. The Angular docs doesn't cover this particular scenario.




Aucun commentaire:

Enregistrer un commentaire