简体   繁体   English

在Angular材质中设置默认芯片

[英]Set default chip in Angular material

I would select web a default chip when page loads. 页面加载时,我会选择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>

Actually no chip is selected. 实际上没有选择芯片。 What I would is select the first chip of the list. 我要选择的是列表中的第一块芯片。

When I console.log(this.chipsList) I see that all the items selected filed is set to true but no one is focused in UI. 当我console.log(this.chipsList)我看到所有选择的项目都设置为true,但没有人关注UI。

How can I default select a chip? 如何默认选择芯片?

Here's a demo 这是一个演示

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

Try to use index inside ngFor: 尝试在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 https://stackblitz.com/edit/angular-material-chip-default-select-vsexxr?file=app%2Fapp.component.html

Or even better, first : 甚至更好, 首先

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

First set default value in typescript: 首先在打字稿中设置默认值:

tmpindex: number = 0;

Now in your html like this. 现在像这样在您的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>

Here is working example: Set default chip list 这是工作示例: 设置默认芯片列表

Hope this helps!!!! 希望这可以帮助!!!!

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

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