2017-05-27 37 views
0

能否请您告诉我如何使用按钮点击更新角度2中的项目?我将list中的项目与deleteedit按钮相加。当我点击edit按钮时,我在update按钮的输入字段中设置当前项目text。点击update按钮后,我想更新所选项目的text如何使用按钮点击更新角度2中的项目?

这里是我的代码

https://plnkr.co/edit/F4fk8VAPzu24P8wRBY5A?p=preview

deleteItem(item){ 
    console.log(item); 
    var index = this.items.indexOf(item); 
    this.items.splice(index,1); 
    } 

    editItem(item){ 
    this.update =true; 
    console.log(item); 
    var index = this.items.indexOf(item); 
    this.val=this.items[index]; 

    } 

    updateItem(){ 

    } 
+0

yes我接受你的回答 – user5711656

回答

1

您应该使用切换概念来实现此目的。

<button (click)="addItem(name)">ADD Item</button> 
    <button *ngIf="update" (click)="updateItem()">Update</button> 
    <input type="text" name="" [(ngModel)]="name"/> 
    <ul> 
     <li *ngFor="let item of items; let i=index"> 
     <span *ngIf="!item.editMode">{{item.name}}</span> 
     <input type="text" *ngIf="item.editMode" [(ngModel)]="item.name"/> 
     <button (click)="deleteItem(item)">X</button> 
     <button (click)="item.editMode= !item.editMode">Edit</button> 
     </li> 
    </ul> 

更新plunker

0

尝试下面的代码,有CURRENTINDEX作为全局变量来跟踪当前索引的;

currentIndex=0; 
editItem(item){ 
this.update =true; 
console.log(item); 
var index = this.items.indexOf(item); 
this.currentIndex = index; 
this.val=this.items[index]; 
} 

updateItem(){ 
    this.items[this.currentIndex] = this.val; 
} 
0

无需使用全局变量

您已经创建了内部editItem指数变量();改用this.index。 https://plnkr.co/edit/nllh0YZzcMACexiMZwFy?p=preview

//our root app component 
import {Component, NgModule, VERSION} from '@angular/core' 
import {BrowserModule} from '@angular/platform-browser' 

@Component({ 
    selector: 'my-app', 
    template: ` 

<div> 
    <h1>{{title}}</h1> 
    <button (click)="addItem()">ADD Item</button> 
    <button *ngIf="update" (click)="updateItem()">Update</button> 
    <input type="text" name="" (keyup)="onKeyP($event)" [value]="val"/> 
    <ul> 
     <li *ngFor="let item of items"> 
     <span>{{item}}</span> 
     <button (click)="deleteItem(item)">X</button> 
     <button (click)="editItem(item)">Edit</button> 
     </li> 
    </ul> 
</div> 

    `, 
}) 
export class App { 
    title = 'Times point'; 
    name ="hellxo"; 
    val ="defual"; 
    items=[]; 
    update=false; 
    onKeyP(event){ 
    console.log(event.target.value); 
    this.val=event.target.value 
    } 

    addItem(){ 
    if(this.val){ 
    this.items.push(this.val); 
    this.val =''; 
    } 
    } 
    deleteItem(item){ 
    console.log(item); 
    var index = this.items.indexOf(item); 
    this.items.splice(index,1); 
    } 

    editItem(item){ 
    this.update =true; 
    console.log(item); 
    var index = this.items.indexOf(item); 
    this.val=this.items[index]; 

    } 

    updateItem(){ 

    } 
} 

@NgModule({ 
    imports: [ BrowserModule ], 
    declarations: [ App ], 
    bootstrap: [ App ] 
}) 
export class AppModule {}