NgClass对函数无反应

问题描述 投票:0回答:1

我在NgClass中使用一个函数,该函数使用ngOnInit中填充的数组。

ngOnInit-> prepareRezerwation()创建colorRezerwation veriable:

    this.nodeService.getRezerwations(this.minMax).subscribe(rezerwations => { 
    this.prepareRezerwation(rezerwations);
    //   this.functionsService.showRezerwation(post, this.openingHours);
      // this.showSpinner = false;
    }, error => {
       console.log("Connection problem")
    }); 

html-> [ngClass] =“ setColor(1,i):

<ng-container matColumnDef="big">
    <th mat-header-cell *matHeaderCellDef class="xunk-calendar-cell"></th>
    <td mat-cell *matCellDef="let element; let i = index" [ngClass]="setColor(1,i)">Name</td>
</ng-container>

setColor(1,i):

  setColor(colIndex, rowIndex){
    this.colorRezerwation.position.forEach(arrayItem => {
      if(arrayItem.column === colIndex && arrayItem.row === rowIndex){
        return {'reservation': true}
      } 
    });
  }

当我跳过整个forEach返回时,它可以正常工作。

谢谢您的所有帮助。

angular typescript ng-class
1个回答
0
投票

您正在将函数内的类变量返回到forEach循环而不是setColor函数。

setColor(colIndex, rowIndex){
    this.colorRezerwation.position.forEach(arrayItem => {
      if(arrayItem.column === colIndex && arrayItem.row === rowIndex){
   -->  return {'reservation': true} <-- this does not return to setColor
      } 
    });
}

您需要在forEach循环之外声明并保存变量,然后返回该变量:

setColor(colIndex, rowIndex){
    let class;
    this.colorRezerwation.position.forEach(arrayItem => {
      if(arrayItem.column === colIndex && arrayItem.row === rowIndex){
        class = {'reservation': true}
      } 
    });
    return class;
  }

或更妙的是,使用查找功能:

setColor(colIndex, rowIndex) {
  return this.colorRezerwation.position
    .find(arrayItem => (arrayItem.column === colIndex && arrayItem.row === rowIndex));
}
© www.soinside.com 2019 - 2024. All rights reserved.