EluciusFTW
EluciusFTW

Reputation: 2615

Angular material selection list with add functionality

I want to use an angular selection list, but additionally, I'd like the user to be able to add new items to the list. If he has already selected a few, this selection should not get lost.

Usually, I'd add a method in the component to add the element to the data list, and then recreate the MatSelectionList I am binding to the view. But then the current selection is lost.

I've tried variations of this in the component (beware, it's pseudo-code):

@ViewChild("items", { static: true }) items: ElementRef;

addItem(item: Item): void {
    var selectionList = <MatSelectionList><unknown>this.items
    
    // Hoped to find something like: 
    // selectionList.options.add(...):

    // or recreate the source, and remembering the selection: 
    // let selected = selectionList.selectedOptions.selected.map(s => s.value);
    // this.items = new MatSelectionList(this._originalItems.push(newItem))
    // this.items.selectedOptions.setSelected(...)
}

Upvotes: 0

Views: 996

Answers (1)

Emilien
Emilien

Reputation: 2761

According to the Selection List Example, you would be able to do this (not tested) :

<input placeholder="Enter new item" [(ngModel)]="newItem" />
<button (click)="addItem()">Add</button>

<mat-selection-list #shoes>
  <mat-list-option *ngFor="let shoe of typesOfShoes">
    {{shoe}}
  </mat-list-option>
</mat-selection-list>

<p>
  Options selected: {{shoes.selectedOptions.selected.length}}
</p>
newItem: string;
typesOfShoes: string[] = ['Boots', 'Clogs', 'Loafers', 'Moccasins', 'Sneakers'];

addItem(): void {
  this.typesOfShoes.push(this.newItem);
}

Upvotes: 1

Related Questions