Angular2新手,所以我试着保持简单。我知道我应该将我的功能组件分开,但现在我只想让它工作。
我的目标是绑定按钮单击的值并在新范围内显示该输出,并将选取的时间值增加1。
编辑:我更新了组件以反映显示随机生成的工程师名称的工作版本。现在是时候增加了。
模板:
<h1>{{title}}</h1>
<p>Engineers:</p>
<ul>
<li *ngFor="let engineer of engineers">
<span>{{ engineer.name }} has been picked: {{ engineer.timesPicked }} times!</span>
</li>
</ul>
<div>
<button (click)="getEng($event)">Pick an Engineer</button>
<span> {{ pickedEngineer }} </span>
</div>
组件:
import { Component } from '@angular/core';
import { Engineer } from './engineer'
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
title = 'Engineers';
engineers = [
new Engineer("Jim", 0),
new Engineer("John", 0),
new Engineer("Bob", 0)
];
myEng = this.timesPicked;
pickedEngineer = '';
getEng(){
var number = Math.random() * 100;
if (number > 0 && number <= 34) {
var pickedEngineer = "Jim";
} else if (number > 34 && number <= 66 ){
var pickedEngineer = "John";
} else {
var pickedEngineer = "Bob";
}
this.pickedEngineer = pickedEngineer;
console.log(pickedEngineer);
}
}
类别:
export class Engineer {
constructor(
public name: string,
public timesPicked: number) {}
}
答案 0 :(得分:0)
您应该删除pickedEngineer
属性并绑定到myEng
属性name
。
<span> {{ myEng?.name }} </span>
在getEng()
方法中,指定新的myEng
并更新myEng.timesPicked
值。
编辑: 模板更改:
<div>
<button (click)="getEng()">Pick an Engineer</button>
<span> {{ myEng?.name}} </span>
</div>
组件变更:
getEng(){
var number = Math.random() * 100;
if (number > 0 && number <= 34) {
this.myEng = this.engineers[0];
this.myEng.timesPicked++;
} else if (number > 34 && number <= 66 ){
this.myEng = this.engineers[1];
this.myEng.timesPicked++;
} else {
this.myEng = this.engineers[2];
this.myEng.timesPicked++;
}
}
我的编辑能够让他对答案给予肯定,但也纠正了他们提交的原始组件的小堆栈跟踪错误: