angular - 如何从数组中预选数据到 mat-selection-list

标签 angular angular-material2

我从 API 得到这样的字符串 55,118,122,126,116,58,125,119,132。 这些是ID。我有一个 Angular 垫选择列表。我想最初选择这些值。所以,基本上我想更新现有数据并将其再次发送到。

这是我的垫子选择列表。

 <mat-selection-list #yuvakslist  [(ngModel)]="preselectedOptions" 
(selectionChange)="onChangeYuvak()">
<mat-list-option *ngFor="let yuvak of yuvaks" class="mt-1" [value]="yuvak.user_id">
          <nb-user name="{{yuvak.cnt_first_name + ' ' + 
 yuvak.cnt_last_name}}" size="large" title="{{yuvak.cnt_mobile_no}}"
          picture="{{thumbnailImg}}{{yuvak.profile_picture}}">
          </nb-user>
        </mat-list-option>
      </mat-selection-list>

我试过将从 API 收到的所有 ID 分配给这样的数组。

const preselectedOptions: Number[] = data.data.present_contact;

我想将这些值预选到 mat-selection-list 中。所以,我可以更新表格。

最佳答案

最好使用 angular reactive forms 而不是 ngModel来完成这个。

这是一个例子

app.component.html

<mat-form-field>
    <mat-select placeholder="Users" [formControl]="userForm" multiple>
        <mat-option *ngFor="let user of userList" [value]="user">
            {{user.name}}
        </mat-option>
    </mat-select>
</mat-form-field>

app.component.ts

import {Component} from '@angular/core';
import {FormControl} from '@angular/forms';

@Component({
    selector: 'app',
    templateUrl: 'app.component.html'
})
export class AppComponent {
    userList: any[] = [
        { name: 'Robin', id: 1 }, 
        { name: 'Pandey', id: 2 }
    ];
    userForm: FormControl;

    constructor() {
        this.userForm = new FormControl([this.userList[0]]);
    }
}

关于angular - 如何从数组中预选数据到 mat-selection-list,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54210491/

相关文章:

validation - Angular 2 paper-input 和表单处理

angular - 解密传入响应 Angular 9

Angular 从另一个指令添加 fxFlex 指令

Angular 2 Material 日期选择器ngModel不显示值

angular - 模板解析错误 : 'md-grid-tile' is not a known element

javascript - 单击 window.print() 中的按钮打印所选页面(而单击按钮不发送页面)?

javascript - Angular 2 和 Laravel 5.2 - 显示不同的 Blade 模板

angular - HttpParams 设置为空

angular-material2 - MatDatepickerFilter-筛选器函数无法访问类变量

angular - 滑动时 Mat Slider 值未更新