首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >从matchip角中的选定属性调用函数的有效方法

从matchip角中的选定属性调用函数的有效方法
EN

Stack Overflow用户
提问于 2021-07-29 10:39:17
回答 2查看 127关注 0票数 0

我做了一个像下面这样的垫片。

HTML

代码语言:javascript
复制
<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:

代码语言:javascript
复制
 isSelected(chip:any) {        
    return this.chipCollection.get(chip.value);
 }

问题:

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

EN

回答 2

Stack Overflow用户

发布于 2021-07-29 10:42:15

您的问题是,isSelected在绑定selected=“isSelected(芯片)”中被调用,这意味着每当该角度运行变化检测时,它都会被调用。

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

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

票数 0
EN

Stack Overflow用户

发布于 2021-07-29 10:46:42

这已被multiple times already清除。

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

控制器(*.ts)

代码语言:javascript
复制
// 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)

代码语言:javascript
复制
<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>
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/68574429

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档