Lucie Schaffner
Lucie Schaffner

Reputation: 35

Display text on a button click Angular

I've created three buttons with ngFor, each button has it own name which is stocked in the array: buttonData[]. buttonData also contains texts and images. What I'm trying to achieve here is when I click on one of my buttons a text and an image appears, each button has its own text and image of course. I can't understand why my function doesn't work since I have no error. Here is my code:

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>

The three variables textprediction, textrebalancing and textvisualization is some text that I get from my json file. I can't understand why it works when I declare my function this way:

  onTitleClick() {
    this.text = this.textprediction;
  }

But when I ask my function to go and get it in my array it doesnt work.

Upvotes: 0

Views: 7185

Answers (1)

Sajeetharan
Sajeetharan

Reputation: 222522

You should pass button to the function

  <button (click)="onTitleClick(button)">

and set it as

 onTitleClick(btnVal:any) {
    this.text = btnVal.description;
  }

Upvotes: 1

Related Questions