typescript 在 Angular 2 的文本框中绑定值
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/41181243/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Bind value in textbox in Angular 2
提问by Hitesh
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.
我在 html 文件中有一个按钮 btnAdd 、一个文本框和一个带有编辑按钮 btnEdit 的列表。当我单击 btnAdd 时,它将文本框值插入到列表中,当单击 btnEdit 时,我想将列表的选定值显示到文本框中。
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 :
下面是 Html 代码:
<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,
谢谢,
回答by Bazinga
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;
}
}