0

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(...)
}

1 Answer 1

1

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);
}
Sign up to request clarification or add additional context in comments.

1 Comment

Omg, so simple, and it works, thank you. I remembered that for material tables you have to recreate the dataSource, so I didn't even try this direct approach.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.