Gaurav
Gaurav

Reputation: 1

How to update the UI when updating the component using another sibling component in aurelia

In navbar class I'm trying to call TodoList class addTodoToList method to add todos but the todos are appending in the items array of Todo Class but not showing on UI in form of list. If i harcode the items in todo class they appear in list. I'm unable to understand the issue.

Navbar Class

import {autoinject, bindable} from 'aurelia-framework';
import {Router} from 'aurelia-router';
import { TodoList } from 'components/TodoList/todo-list';

@autoinject
export class navbar {
    // Binding it with the newItem of the action-area class to access it
    @bindable public newItem: string;
    // items: string[];

    constructor(private router: Router, private todos: TodoList) {
        // this.items = [];
    }

    // Basic logout functionality
    logout(): void {
        console.log('logout clicked');
        this.router.navigate("");
    }

    // Adds todo to the todo-list
    addTodo(): void {
        const todoText = this.newItem; 
        if(todoText === undefined || todoText === '') {
            alert("Please enter the valid Todo");
        } else {
            // this.items.push(todoText);
            this.todos.addTodoToList(todoText);
            this.newItem = '';
        }
    }


    deleteTodo() {}

    updateTodo() {}
}

todo-list.ts Class

import {autoinject, BindingEngine} from 'aurelia-framework';

@autoinject
export class TodoList {
    items: string[];

    constructor() {
        this.items = [];
    }

    addTodoToList(todoText: string): void {
        this.items.push(todoText);
        console.log(this.items)
    }
}

todo-list.html

<template>
    <ul>
        <li repeat.for="item of items">
           ${item}
        </li>
    </ul>
</template>

Upvotes: 0

Views: 32

Answers (1)

W.Kurek
W.Kurek

Reputation: 309

The reason why invoking addTodoToList(item) method in Navbar class does not cause changes in TodoList component rendered view is that todos object that is being injected to Navbar class is not referencing the rendered <todo-list> component ViewModel.

To mainipulate items list of TodoList component you need to take one of following strategies:

  1. Access refrence to rendered <todo-list> component using view-model.ref="expression" syntax and pass it to Navbar component - AURELIA DOCUMENATTION HERE
  2. Create service to store todo items and inject it to both Navbar and TodoList components
  3. Use EventAggregator interface. Publish events in navbar component when manipulating todo list and subscribe to those events in TodoList component

Basing on scarse information that you have given I whold suggest solution 2 - creating separate service for storing items and at the same time being single source of truth.

Upvotes: 1

Related Questions