【问题标题】:Angular material selection list with add functionality具有添加功能的角材料选择列表
【发布时间】:2020-12-13 05:40:44
【问题描述】:

我想使用角度选择列表,但另外,我希望用户能够向列表中添加新项目。如果他已经选择了一些,那么这个选择应该不会丢失。

通常,我会在组件中添加一个方法以将元素添加到数据列表中,然后重新创建MatSelectionList 我正在绑定到视图。但随后当前的选择就丢失了。

我已经在组件中尝试过这种变体(注意,它是伪代码):

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

【问题讨论】:

    标签: angular angular-material


    【解决方案1】:

    根据Selection List Example,您可以这样做(未经测试):

    <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);
    }
    

    【讨论】:

    • 天啊,很简单,而且很有效,谢谢。我记得对于材料表,您必须重新创建数据源,所以我什至没有尝试这种直接方法。
    猜你喜欢
    • 2016-10-22
    • 1970-01-01
    • 1970-01-01
    • 2020-09-20
    • 1970-01-01
    • 2020-08-30
    • 1970-01-01
    • 2020-02-26
    • 1970-01-01
    相关资源
    最近更新 更多