【问题标题】:mat-select value is not showing垫选择值未显示
【发布时间】:2018-10-09 23:08:44
【问题描述】:

我有一个view 我的Angular Components 一个mat-select。 这个Angular Component 有一个用于编辑一些数据的表单。所以这个想法是当我打开组件视图时,表单是预填充的。

  <mat-form-field> 
          <mat-select
            [(value)]="selectedGroups"
            placeholder="Select the associated Bitbucket groups ..."
            multiple>

            <mat-option
            *ngFor="let group of bitbucketgroupsList?.results"
            [value]="group.id">{{group.bitbucket_group}}
            </mat-option>
           </mat-select> 
   </mat-form-field>

这是ngOnInit函数:

selectedGroups = [];
ngOnInit() {
    this.sub = this.route.params.subscribe(params => {
        this.id = +params['id'];
    });
    this.EditteamForm = this._fb.group({
        name: ['', Validators.required],
        description: ''
    });
    let url = this.baseUrl + `/teams/${this.id}`;
    this.httpClient.get(url).subscribe((data: Array<any>) => {
        this.EditteamForm.controls['name'].setValue(data['results'][0]['name']);
        this.EditteamForm.controls['description'].setValue(data['results'][0]['description']);
        for (let i = 0; i < data['results'][0]['bitbucket_group'].length; i++) {
            let value = data['results'][0]['bitbucket_group'][i]['id'];
            this.selectedGroups.push(value);
        }

    });
}

我在ngOnInit 中所做的是发送HTTP request 以获取团队的实际数据并将它们显示在表单中(预填表单),然后让用户更改它们。 我的问题是,当我打开具有表单的视图时,在 mat-select 字段中没有选择 selectedGroups 的值。即使我有另一个具有相同逻辑的组件,它也可以正常工作。在这里,我不知道我错过了什么。 当我执行console.log(this.selectedGroups) 时,我看到列表有一个值,但它没有显示在mat-select 中。 有什么线索吗?

【问题讨论】:

  • 试试 [(ngModel)]="selectedGroups"
  • ngModel 在 Angular 6 中已弃用,我使用的是反应式表单,因此 ngModel 不兼容。它给出了这个错误:ERROR Error: " ngModel cannot be used to register form controls with a parent formGroup directive
  • 你能发布你的console.log()的输出吗?
  • 那么代码中的formControl在哪里
  • @Chellappan 我使用 formControl 进行简单的输入。对于选择输入,我使用 [(value)]

标签: angular typescript angular-material


【解决方案1】:

使用 compareFn 函数告诉 Angular 如何比较值。

自定义默认选项比较算法, 支持 compareWith 输入。 compareWith 接受一个有两个的函数 参数:option1 和 option2。如果给出 compareWith,Angular 通过函数的返回值选择选项

参考:https://angular.io/api/forms/SelectControlValueAccessor

<mat-form-field>
  <mat-select placeholder="Toppings"
  [compareWith]="compareFn" 
   [(value)]="toppings" multiple>
    <mat-option *ngFor="let topping of toppingList" [value]="topping">{{topping.name}}</mat-option>
  </mat-select>
</mat-form-field>

例如:https://stackblitz.com/edit/angular-ad3eqa-s3f4z1

【讨论】: