3d cartoon hands holding a phone

Unlock full course by purchasing a membership

Lesson 10

Toggling Item State

Completing a checklist item

STANDARD

Toggling Item State

We have the ability to add items, but now we need to extend their functionality to allow for indicating that a particular item has been complete. We also want the ability to “reset” the completion state of a particular checklist.

Add the ability to toggle to the service

Add the following method to the ChecklistItemService:

  toggle(itemId: string) {
    const newItems = this.checklistItems$.value.map((item) =>
      item.id === itemId ? { ...item, checked: !item.checked } : item
    );

    this.checklistItems$.next(newItems);
  }

We’re doing a similar thing to what we usually do here, but rather than just adding a new value on to the existing values we are modifying the values. We map through each item in the array and we check if its id matches the itemId being passed in. If it does, we use the spread operator to create a new object containing all of the same properties as the old item object, except we overwrite checked with the opposite of whatever it is currently:

{ ...item, checked: !item.checked }

Otherwise, we just return the item unchanged.

Add a checkbox to the checklist item

Add a checkbox to the template of the ChecklistItemListComponent:

    <ion-list lines="none">
      <ion-item *ngFor="let item of checklistItems; trackBy: trackByFn">
        <ion-label>{{ item.title }}</ion-label>
        <ion-checkbox slot="end" [checked]="item.checked"></ion-checkbox>
      </ion-item>
    </ion-list>

We have added a simple checkbox and we are binding its checked state to the checked value from the item. This leads us into an interesting discussion about our architecture.

Emit a toggle event

The items for this component are supplied by an input:

@Input() checklistItems!: ChecklistItem[];

It is out parent component, the ChecklistComponent that actually handles managing the checklist item data. When this item is clicked, it is not the role of our ChecklistListItemComponent to manage updating that data for the application, it is the role of our parent smart component the ChecklistComponent.

What we will do to handle this is just have our dumb component emit a toggle event whenever a specific item is clicked. Then the smart parent component can react to that event and make the state changes necessary in the application.

STANDARD
Key

Thanks for checking out the preview of this lesson!

You do not have the appropriate membership to view the full lesson. If you would like full access to this module you can view membership options (or log in if you are already have an appropriate membership).