繁体   English   中英

在Angular材质中设置默认芯片

[英]Set default chip in Angular material

页面加载时,我会选择Web作为默认芯片。

     <mat-chip-list #chipsList >
        <mat-chip (click)="selectedChip(elm)" color="accent" selected="true" *ngFor="let elm of objectKeys" [value]="elm" color="accent">
          {{elm}}
        </mat-chip>
      </mat-chip-list>

实际上没有选择芯片。 我要选择的是列表中的第一块芯片。

当我console.log(this.chipsList)我看到所有选择的项目都设置为true,但没有人关注UI。

如何默认选择芯片?

这是一个演示

尝试将selected =“ Web”更改为[selected] =“ this.selected === elm”

尝试在ngFor中使用索引

 <mat-chip (click)="selectedChip(elm)" color="accent" [selected]="index === 0" *ngFor="let elm of objectKeys; let index = index" [value]="elm" color="accent">
          {{elm}}</mat-chip>
      </mat-chip-list>

https://stackblitz.com/edit/angular-material-chip-default-select-vsexxr?file=app%2Fapp.component.html

甚至更好, 首先

[selected]="first" *ngFor="let elm of objectKeys; let first = first"

首先在打字稿中设置默认值:

tmpindex: number = 0;

现在像这样在您的html中。

<mat-chip (click)="selectedChip(elm);tmpindex=i;" 
          color="accent" [selected]="i===tmpindex" 
          *ngFor="let elm of objectKeys; let i = index" 
          [value]="elm" color="accent">
     {{elm}}</mat-chip>
</mat-chip-list>

这是工作示例: 设置默认芯片列表

希望这可以帮助!!!!

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM