简体   繁体   中英

Set default chip in Angular material

I would select web a default chip when page loads.

     <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.

How can I default select a chip?

Here's a demo

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

Try to use index inside 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

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.

<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!!!!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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