Home > Software engineering >  Angular Material Selection List - set checked columns in template
Angular Material Selection List - set checked columns in template

Time:11-26

I have a material selection list:

<mat-selection-list #pickedCols [(ngModel)]="selectedColumns" (ngModelChange)="onPickColumns($event)">
  <mat-list-option *ngFor="let colVal of availableColumns" 
    [selected]="????" <!-- Here i've tried for example selectedColumns.indexOf(colVal) > 0 which doesnt work either -->
    [value]="colVal">{{colVal}}</mat-list-option>
</mat-selection-list>

I want to set the [selected] attribute to true or false depending on whether the string value tied to the Mat-list-option is available in the selectedColumns list. Im not sure how I can determine that the options should be checked or not.

in the ngOnInit i get the columns as a list of strings:

ngOnInit() {
   cols = getColsFromLocalStorage() // ["a", "b", "c"];
   this.selectedColumns = cols // doesnt work
}

onPickColumns(elements: string[]){
  updateColsInLocalStorage(elements);
}

I feel like im missing something really basic..

CodePudding user response:

You don't even need to bind selected. It's set by default if the value is available in the list.

selectedColumns = ['a','b']
availableColumns = ['a','b','c','d']
//This will auto select options 'a', 'b' for you
  • Related