【发布时间】:2018-08-30 11:41:51
【问题描述】:
我用 ngFor 创建了三个按钮,每个按钮都有自己的名称,存储在数组中:buttonData[]。 buttonData 还包含文本和图像。 我在这里想要实现的是,当我单击其中一个按钮时,会出现一个文本和一个图像,当然每个按钮都有自己的文本和图像。 我不明白为什么我的功能不起作用,因为我没有错误。 这是我的代码:
component.ts
import { Component, OnInit } from '@angular/core';
import { FeaturesService} from '../features.service';
@Component({
selector: 'app-features',
templateUrl: './features.component.html',
styleUrls: ['./features.component.css']
})
export class FeaturesComponent implements OnInit {
constructor(private featuresService: FeaturesService ) { }
title = 'Features';
textprediction: String;
textrebalancing: String;
textvisualization: String;
text = '';
img = '';
buttonData = [
{
title: 'Prediction',
description: this.textprediction,
img: '../../assets/prediction.png'
},
{
title: 'Rebalancing',
description: this.textrebalancing,
img: '../../assets/rebalancing.png'
},
{
title: 'Visualization',
description: this.textvisualization,
img: '../../assets/visualization.png'
}
];
ngOnInit() {
this.featuresService.getFeatures().subscribe(value => {
console.log(value);
this.textprediction = value[1].textprediction;
});
this.featuresService.getFeatures().subscribe(value => {
console.log(value);
this.textrebalancing = value[2].textrebalancing;
});
this.featuresService.getFeatures().subscribe(value => {
console.log(value);
this.textvisualization = value[3].textvisualization;
});
}
onTitleClick(i: number) {
this.text = this.buttonData[i].description;
this.img = this.buttonData[i].img;
}
}
component.html
<h1>{{title}}</h1>
<tr class="btn-group" *ngFor="let button of buttonData; let i = index">
<td>
<button (click)="onTitleClick(i)">
{{button.title}}
</button>
</td>
</tr>
三个变量 textprediction、textrebalancing 和 textvisualization 是我从我的 json 文件中获得的一些文本。 当我以这种方式声明我的函数时,我不明白为什么它会起作用:
onTitleClick() {
this.text = this.textprediction;
}
但是当我要求我的函数去我的数组中获取它时它不起作用。
【问题讨论】:
-
在您绑定文本和 img 变量的模板中?
-
无处,我不知道如何声明它们
-
如果你不知道如何以及在哪里使用,那么你怎么能说我的按钮仍然不显示我的文本和图像
-
喜欢这个?
<h1>{{title}}</h1> <tr class="btn-group" *ngFor="let button of buttonData"> <td> <button onclick="onTitleClick(button)"> {{button.title}} <ng-template>{{button.description}} {{button.img}}</ng-template> </button> </td> </tr>
标签: html angular typescript button ngfor