本文介绍了在Angular 2中单击按钮时更新列表项的值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个按钮btnAddUpdate,一个文本框和一个带有html文件中的编辑按钮btnEdit的列表.当我单击btnAdd时,它会在列表中插入一个文本框值;当单击btnEdit时,它将在文本框中显示选定的值,现在我想在列表中更新该值.
I have a button btnAddUpdate, a textbox and list with a edit button btnEdit in a html file. When I click on btnAdd it insert a textbox value into list and when click on btnEdit, it will display selected value in textbox and now I want to update that value in list.
下面是我的组件代码:
import { Component } from '@angular/core';
import {Hero} from './hero';
@Component({
selector: 'my-Home',
templateUrl: 'app/Home/home.component.html',
})
export class HomeComponent {
title = 'Tour of Heroes';
newH : Hero;
heroes = [new Hero(1, 'Windstorm'), new Hero(13, 'Bombasto'),new Hero(15, 'Magneta'), new Hero(20, 'Tornado')];
// If not in list please add else Update list value.
addHero(newHero:string) {
this.title ="Button Clicked";
if (newHero) {
let hero = new Hero(14,newHero);
this.heroes.push(hero);
}
}
selectedHero = '';
onEdit(hero: Hero) {
this.selectedHero = hero.name;
}
下面是html代码:
<input type='text' [value]="selectedHero" #heroName/>
<button (click)="addHero(heroName.value)">Add Hero!</button>
<ul>
<li *ngFor="let hero of heroes" >
<span >{{ hero.id }}</span> {{ hero.name }}
<button (click)=onEdit(hero)>Edit!</button>
</li>
</ul>
推荐答案
import {Component, NgModule} from '@angular/core'
import {BrowserModule} from '@angular/platform-browser'
import {FormsModule} from '@angular/forms';
export class Hero {
constructor(public id: number, public name: string){}
}
@Component({
selector: 'my-app',
template: `
<input type="text" [(ngModel)]="heroName" />
<button (click)="addHero()">Add Hero!</button>
<ul>
<li *ngFor="let hero of heroes">
<span>{{ hero.id }}</span> {{ hero.name }}
<button (click)="onEdit(hero)">Edit!</button>
</li>
</ul>
`,
})
export class App {
heroName: string = '';
heroes: Array<Hero> = [new Hero(1, 'One'), new Hero(2, 'Two')];
lastName: string;
addHero() {
const findHero = this.heroes.find(hero => hero.name === this.lastName);
if(findHero) {
findHero.name = this.heroName;
} else {
this.heroes.push(new Hero(3, this.heroName));
}
this.heroName = '';
}
onEdit(hero) {
this.lastName = hero.name;
this.heroName = hero.name;
}
}
@NgModule({
imports: [ BrowserModule, FormsModule ],
declarations: [ App ],
bootstrap: [ App ]
})
export class AppModule {}
这篇关于在Angular 2中单击按钮时更新列表项的值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!