Reputation: 1228
I have a button btnAdd , 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 I want to display selected value of list into Text box.
Below is my Component Code:
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')];
addHero(newHero:string) {
this.title ="Button Clicked";
if (newHero) {
let hero = new Hero(14,newHero);
this.heroes.push(hero);
}
}
onEdit(hero: Hero) {
// want to display selected name in textbox.
}
}
Below is Html code :
<input type = 'text' #newHero/>
<button (click)=addHero(newHero.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>
Below is my class :
export class Hero {
constructor(
public id: number,
public name: string) { }
}
Thanks,
Upvotes: 0
Views: 16257
Reputation: 11194
You can bind the hero name to the input text value:
<input type='text' [value]="selectedHero" #heroName/>
<button (click)="addHero(heroName.value)">Add Hero!</button>
export class HomeComponent {
selectedHero = '';
onEdit(hero: Hero) {
this.selectedHero = hero.name;
}
}
Upvotes: 1