0

我正在显示一个用户列表,其中每个用户都有一个显示按钮。单击时,我想通过相应用户的图表显示数据。我编写了一个切换逻辑,效果很好,但是如果我单击第一个用户上的按钮,然后单击第二个用户,而不是显示第二个用户的数据,它会隐藏前一个图表,但不显示当前行的任何数据。

切换逻辑(user.component.ts)

toggle() {
    this.visible = !this.visible;
    if (this.visible) {
      console.log('enter');
      this.show.emit(this.visible);
    } else {
      this.show.emit(null);
    }
  }

用户列表html代码

<div class="container">
  <table class="table">
    <thead class="thead-dark">
      <tr>
        <th scope="col">First</th>
        <th scope="col">city</th>
        <th></th>
      </tr>
    </thead>
    <tbody>
      <tr *ngFor="let user of users,index as i" >

          <td>{{ user.name }}</td>
          <td>{{ user.city }}</td>
          <td><button id= "i" class="btn btn-success" (click)= "toggle()">show</button></td>
         </tr>

    </tbody>
  </table>

</div>

图形

rating: Rating[] = [];
   @Input() flag = false;


  constructor(private dataService: DataService) { }

  ngOnInit() {
    console.log('init');
    var myChart= new Chart('myChart', {
      type: 'bar',
      data: {
          labels: ['Technical', 'Communication', 'Experience', 'Leadership'],
          datasets: [{
              label: 'skill scores',
              data: [10,15, 16, 22],
              backgroundColor: [
                  'rgba(255, 99, 132, 0.2)',
                  'rgba(54, 162, 235, 0.2)',
                  'rgba(255, 206, 86, 0.2)',
                  'rgba(75, 192, 192, 0.2)'

              ],
              borderColor: [
                  'rgba(255, 99, 132, 1)',
                  'rgba(54, 162, 235, 1)',
                  'rgba(255, 206, 86, 1)',
                  'rgba(75, 192, 192, 1)'

              ],
              borderWidth: 1
          }]
      },
      options: {
          scales: {
              yAxes: [{
                  ticks: {
                      beginAtZero: true
                  }
              }]
          }
      }
  });
  }



图表 html

<div style="height:40%;width:40%;" class="center" [hidden] ="!flag" >
  <canvas
  class="chart chart-bar"
  chart-data="dataChart" id  = "myChart"></canvas>
</div>

true 和 null 被传递给图形组件,该组件根据传递的值显示图形。在调试时我发现这是因为,所有用户都有一个通用的切换功能。但想不出一种方法来分别为每个用户实现切换功能。希望我清楚,任何建议

4

1 回答 1

0

您拥有的一种选择是将布尔值更改isVisible为用户的 id: visibleUserId?: number

您的切换功能将类似于:

toggle(id: number) {
    this.visibleUserId = id === this.visibleUserId ? null : id;
    this.show.emit(this.visibleUserId);
  }

并在标记中:

<button id= "i" class="btn btn-success" (click)= "toggle(user.id)">show</button>

现在,当在 上发出一个 id 时Output() show,这就是您应该为其显示图表的用户的 id。如果它为空,那么您不应该显示任何图表。

于 2020-06-30T16:10:40.330 回答