首页 > 解决方案 > 在 HTML 中使用插值来减少代码

问题描述

在我之前的问题 链接 中,感谢@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

标签: angular

解决方案


你不能使用插值。

您应该使用相同的名称 -#card对所有这些元素,然后使用ViewChildren在 ts 文件中获取这些元素

我分叉了你的 stackblitz 并对其进行了编辑以在这里工作。

代码应该看起来像。

@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>


推荐阅读