【问题标题】:Efficent way to call a function from a selected attribute in matchip angular从mat芯片角度中的选定属性调用函数的有效方法
【发布时间】:2021-10-05 00:33:16
【问题描述】:

我已经创建了一个如下图所示的垫子。

HTML

<mat-chip-list multiple>
    <mat-chip class="chip_margin cursor mt-3" *ngFor="let chip of chips" selectable="true"
     [selected]="isSelected(chip)" (click)="onClick($event, chip);">
   <span class="unselectableText">{{chip.ViewValue}}</span>
    </mat-chip>
</mat-chip-list>

TS:

 isSelected(chip:any) {        
    return this.chipCollection.get(chip.value);
 }

问题:

“isSelected”函数调用n次如何解决这个问题。 提前致谢。

【问题讨论】:

    标签: javascript angular angular-material


    【解决方案1】:

    您的问题是 isSelected 在绑定 [selected]="isSelected(chip)" 中被调用,这意味着每次该角度运行更改检测时都会调用它。

    为避免这种情况,您有两种解决方案,第一种是在另一个地方计算 isSelected 并存储一个变量。

    第二种解决方案可能是切换到 OnPush 更改检测,但您必须处理这样一个事实,即更改检测只会在输入更改时运行。

    【讨论】:

      【解决方案2】:

      这已被清除multipletimesalready

      其中一个修复方法是在 this.chips 成员变量的初始化期间执行控制器 (*.ts) 中的函数。

      控制器 (*.ts)

      // assuming `this.chips` is initialized in a subscription
      
      this.someService.getChips().pipe(
        map((chips: any) =>                    // <-- RxJS `map` operator
          chips.map((chip: any) => ({          // <-- JS `Array#map` function
            ...chip,
            isSelected: this.isSelected(chip)  // <-- introduce additional property
          })
        )
      ).subscribe({
        next: (chips: any) => this.chips = chips,
        error: (error: any) => console.log(error)
      });
      

      模板 (*.html)

      <mat-chip-list multiple>
        <mat-chip 
          class="chip_margin cursor mt-3" 
          *ngFor="let chip of chips" 
          selectable="true"
          [selected]="chip.isSelected" 
          (click)="onClick($event, chip);"
        >
          <span class="unselectableText">{{chip.ViewValue}}</span>
        </mat-chip>
      </mat-chip-list>
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2020-04-25
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多