显示来自 ngfor 按钮的图像和文本 angular

display images and text from ngfor buttons angular

我正在尝试创建三个按钮,每个按钮显示一个图像和一个文本。 但它不起作用,我不明白为什么。

我想要实现的是,当我点击我的三个按钮之一时,会出现一个图像和文本。这个图像和文本对于每个按钮都是唯一的,我必须使用 ngFor。

这是我的代码:

component.ts

export class FeaturesComponent implements OnInit {
    title = 'Features';

    buttonData = [{
        title: 'Prediction',
        description: 'text',
        img: '../../assets/prediction.png'
    },
    {
        title: 'Rebalancing',
        description: 'text',
        img: '../../assets/rebalancing.png'
    },
    {
        title: 'Visualization',
        description: 'text',
        img: '../../assets/visualization.png'
    }];
}

component.html

<h1>{{ title }}</h1>
<tr class="btn-group" *ngFor="let button of buttonData">
  <td>
    <button (click)="button.description; button.img">{{button.title}}</button>
  </td>
</tr>

我不是有意无礼,但我建议您阅读 angular 文档 here.

中的英雄之旅教程

您的模板有误。这是我认为您正在努力实现的目标的示例:

component.html

<h1>{{ title }}</h1>

<tr class="btn-group" *ngFor="let button of buttonData; i = index">
 <td>
  <button (click)="onButtonTitleClicked(i)">
    {{button.title}}
    <ng-template *ngIf="isButtonTitleClicked[i]">
       <p>{{button.description}}</p>
       <img src="{{button.img}}">
    </ng-tempalte>
  </button>
 </td>
</tr>

component.ts

isButtonTitleClicked: Array<boolean>;

public onButtonTitleClicked(i: number): void {
   # whatever you want to happen when button is clicked
   this.isButtonTitleClicked[i] = true;
}

由于 ngFor 创建了多个按钮,因此您需要知道单击了哪个按钮。因此,我们将 'i = index' 添加到 ngFor,这样我们就有了一种方法来识别单击了哪个按钮。

在组件中我们创建了一个布尔数组,这样我们就可以存储每个按钮的 true/false 状态(点击或未点击)。所以现在当按钮被点击时,我们将该按钮的索引传递给点击方法并在数组中设置值。

ngIf 将仅显示数组成员设置为 true 的那些按钮的模板。

这是一种非常基本的方法。想想用户如何将值设置回false?是否再次单击将其设置为隐藏 - 如果这样做更好:

this.isButtonTitleClicked[i] = !this.isButtonTitleClicked[i];

因为这不会(反转)每次点击的值。

我还建议查看 this question 以及有关将 img 放在按钮上的各种答案。

注意

将这 2 个命名为相同的名称可能不是一个好主意:

onButtonTitleClicked(i) <- 这是调用方法

onButtonTitleClicked[i] <- 这是对数组

的元素 i 的引用