Search code examples
angularangular-ngmodel

`[(ngModel)]` doesn't get value from contoller, how to fix?


I have a todo list project where every entry is an input (inline modification).

<div *ngFor="let t of todos;" class="list-item">
  <span class="list-item__checkbox">&nbsp;</span>
  <textarea class="todo-item__textarea"
    (input)="onTodoKeyEvent($event, t)"
    (keydown)="onTodoKeyEvent($event, t)"
    ([ngModel])="t.text"
    ></textarea>
  {{t.text}}
</div>

The onTodoKeyEvent method invokes update function, to update todo data in array.

onTodoKeyEvent(event, todo) {
  this.updateTodo({
    id: todo.id,
    text: event.target.value + 'additional text'
  });
}

I get todos into controller from service using getter:

get todos(): Todo[] {
  return this.todoDataService.get();
}

Update function:

update(data: Todo) {
  let todo = this.todos[data.id];
  Object.assign(todo, data);
}

The problem is that I can see new data in todos array, and in view at {{t.text}}, but the value inside textarea, model value, is the same as was typed, so it feels like one-way binding. enter image description here

Why is that, how can I fix it? Thank you.


Solution

  • It's [(ngModel)]="t.text", not ([ngModel])="t.text".

    They call it Bananas in a box:

    this is the box: [ ] and these are the bananas: ( )