在HTML中使用插值来减少代码

时间:2019-06-23 19:04:16

标签: angular

在我之前的问题中 link 并感谢@Elma Cherb的回答,我学会了如何使用ngStyle解决我的问题。

我需要扩展问题,以便能够以允许我使用插值方式更改#card10的方式更改代码,以与诸如“ #card” +索引之类的索引结合使用。 或使用以前的解决方案,但不仅要有两个,还要有多个参数。

 <mat-grid-tile *ngFor="let card of cards; let indice=index"
    [style.background]="'#F2F2F2'"
    [style.border]="'1px solid black'"
  >
    <div class="card">
      <div #card10 class="overlay">
        <h4>CONTROL  </h4>
        <div>{{card.name}}</div>
        <br />
        <div>{{card.id}}</div>
        <br />
        <button
          *ngIf="verBoton10"
          class="btn-material"
          (click)="onClickHecho(card.id)"
        >
          Hecho
        </button>
      </div>
    </div>
  </mat-grid-tile>

我已将完整的代码放入https://stackblitz.com/edit/kamishibai

1 个答案:

答案 0 :(得分:0)

您不能对其使用插值。

您应该对所有名称使用相同的名称-#card,然后使用ViewChildren

在ts文件中获取这些元素。

我分叉了您的堆叠闪电战,并对其进行了编辑,使其可以正常工作here

代码应如下所示。

@ViewChildren('card') eleCards: QueryList<ElementRef>;

onClickHecho(index: number) {
  if ( this.horaControl10 < 10 ) {
    this.mensajeControlAntesHora();
  } else {
    this.hechoService.hecho10.emit(true);
    this.verBoton10 = false;
    const card = this.eleCards.toArray()[index];
    if (this.horaControl10 >= 20) {
      this.hechoService.hecho10.emit(false);
      this.mensajeControlDespuesHora();
      this.renderer.setStyle(card.nativeElement, 'backgroundColor', 'orange' );
    } else {
      this.hechoService.hecho10.emit(true);
      this.renderer.setStyle(card.nativeElement, 'backgroundColor', 'green' );
    }
  }
}
<mat-grid-tile *ngFor="let card of cards; let indice=index"
  [style.background]="'#F2F2F2'"
  [style.border]="'1px solid black'"
>
<div class="card">
    <div #card class="overlay">
      <h4>CONTROL</h4>
      <div># Verificar que no existen cristales en la zona.</div>
      <br />
      <div># Otra tarea.</div>
      <br />
      <button
        *ngIf="verBoton9"
        class="btn-material"
        (click)="onClickHecho(indice)"
      >
        Hecho
      </button>
    </div>
  </div>
</mat-grid-tile>