选项未在mat-select中显示或被选中

问题描述 投票:0回答:2

我想在我的mat-select表单中预先选择Angular字段中的一些选项,所以我在typescript文件中有这个代码:

selectedApps = [];
ngOnInit() {
    const url = this.baseUrl + `/projects/${this.id}`;
    this.httpClient.get(url).subscribe((data: Array<any>) => {
        for (let i=0; i<data['results'][0]['apps'].length; i++) {
            this.selectedApps.push(data['results'][0]['apps'][i]['name']);    
        }

    });
}

这是mat-select输入字段:

          <div class="col-sm-8 float-left">

        <mat-form-field> <mat-select
          [(value)]="selectedApps" 
          placeholder="Select the associated applications ..."
          multiple (click)="getAppList();"> <mat-option
          *ngFor="let app of appsList?.results" [value]="app.id">{{app.name
        }}</mat-option> </mat-select> </mat-form-field>
      </div>

我的问题是selectedApps的值不会显示在字段内,即使值已在数组内正确推送。这是为什么?

angular typescript angular-material
2个回答
0
投票

你正在“预选”名字

this.selectedApps.push(data['results'][0]['apps'][i]['name']);  

而您的选项包含ID

<mat-option
          *ngFor="let app of appsList?.results" [value]="app.id">{{app.name
        }}</mat-option>

为了使它工作,selectedApps mush保持与mat-option [value]属性相同的值。毕竟,这将是实际的mat-select值。

说实话,我会把整个app作为一个值,因为没有理由对它进行威胁。它会简化很多代码。


0
投票

我在component.ts文件中添加了一些虚拟数据,我可以在表单字段中看到selectedApps。

在模板文件中

<form>
  <div class="col-sm-8 float-left">
    <mat-form-field> <mat-select
      [(value)]="selectedApps" 
      placeholder="Select the associated applications ..."
      multiple (click)="getAppList();"> <mat-option
      *ngFor="let app of appsList" [value]="app.value">{{app.name
    }}</mat-option> </mat-select> </mat-form-field>
  </div>

并在ts文件中:

export class SelectFormExample {
selectedApps: string;
 appsList = [
 {value: 'app_1', results: 'App1-result', name: 'APP 1'},
{value: 'app_2', results: 'App2-result', name: 'APP 2'},
{value: 'app_3', results: 'App3-result', name: 'APP 3'}
];

getAppList(){
    console.log('getAppList');
  }
© www.soinside.com 2019 - 2024. All rights reserved.