Bean0341 Bean0341 - 1 month ago 15
TypeScript Question

angular 2 Insert new table items to top of table

I have a component that adds TODO's to a table, and I wanted to know how you would go about adding the new TODO's to the top of the table rather than the bottom. I have seen a few answers on SO showing how to achieve this in JS but I wanted to know how to do it with Typescript. Any help would be much appreciated, thank you!

Answer

You can just use unshift to add the item to the begining of your array.

Example http://plnkr.co/edit/7FC8IUvdR3wPevrd48yt?p=preview

 <div>
  <input type="text" [(ngModel)]="newTodo" placeholder="Add New Todo"/>
  <button type="button" (click)="addTodo()">Add</button>
</div>
<div>
  <ul>
    <li *ngFor="let todo of todos">{{todo}}</li>
  </ul>
</div>


export class App {
  newTodo: string;
  todos: Array<string>;

  constructor() {
    this.newTodo = "";  
    this.todos = ["Grocery Shopping", "Banking"];
  }

  addTodo() {
    this.todos.unshift(this.newTodo);
    this.newTodo = "";
  }
}
Comments