垫选择值未显示

时间:2018-10-09 14:47:31

标签: angular typescript angular-material

我的view中的Angular Components中有一个mat-selectAngular 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中。 有任何线索吗?

1 个答案:

答案 0 :(得分:0)

使用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

相关问题