您能否告诉我如何使用按钮点击更新角度2中的项目?我正在使用list
和delete
按钮在edit
中添加项目。当我点击edit
按钮时,我使用text
按钮在输入字段中设置当前项update
。我想在点击text
按钮后更新所选项目的update
。
这是我的代码
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 :(得分: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
答案 1 :(得分: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;
}
答案 2 :(得分: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 {}