angular 2将新表格项目插入表格顶部

时间:2016-10-26 17:01:54

标签: angular typescript

我有一个将TODO添加到表中的组件,我想知道如何将新TODO添加到表的顶部而不是底部。我已经看到了一些关于如何在JS中实现这一点的答案,但我想知道如何使用Typescript。非常感谢任何帮助,谢谢!

2 个答案:

答案 0 :(得分:3)

您可以使用unshift将项目添加到数组的开头。

示例 dispatch()

 <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 = "";
  }
}

答案 1 :(得分:2)

splice 中的 Typescript 功能可用于执行您想要的操作。

DEMO:https://plnkr.co/edit/B5l1fCOvItkt45cJMBKO?p=preview

<input type="text" #newItem>
<button (click)="add(newItem.value)">Add</button>

<table>
    <tr *ngFor="let item of items">
         <td>{{item.name}}</td>
    </tr>
</table>
export class App {

  items=[{name:"Computer"},{name:"Laptop"}];
  add(newItem){
    this.items.splice(0,0,{name:newItem});
  }
}
相关问题