角材料垫选择不加载初始值

时间:2018-09-25 02:21:55

标签: angular6 angular-material-6

我在使用mat-select组件时遇到问题,一切正常,但他只是在编辑时未设置初始值...如果我更改为简单的HTML,一切都会正常。我做错了什么?

效果很好的HTML选择:

<select formControlName="category" [compareWith]="compareFn">
    <option [ngValue]="c" *ngFor="let c of categoriesService.categories$ | async"> {{c.name}}</option>
  </select>

无法按预期方式工作的角材料组件:

<mat-form-field>
    <mat-select placeholder="Category" formGroupName="category" (selectionChange)="setCategoryValueOnForm($event)"
                [compareWith]="compareFn" >
      <mat-option *ngFor="let c of categoriesService.categories$ | async" [value]="c">
        {{c.name}}
      </mat-option>
    </mat-select>
  </mat-form-field>

使用简单的select元素时,我看到我的功能compareFn有效,但是使用Angular Material时,“ y”值始终未定义...

compareFn(x: ICategory, y: ICategory): boolean {
   console.log(x);
   console.log(y);
   console.log('CALLED COMPARE FN');
   return x && y ? x.id === y.id : x === y;
 }

有问题的gif:

enter image description here 我做错了吗?谢谢!

1 个答案:

答案 0 :(得分:0)

我只是意识到我使用的是formGroupName =“ category”,而正确的是formControlName =“ category” ...

<mat-form-field hintLabel="select one">
    <mat-select placeholder="Category" formControlName="category"
                [compareWith]="compareIds">
      <mat-option *ngFor="let c of (categoriesService.categories$ | async)" [value]="c">
        {{ c.name }}
      </mat-option>
    </mat-select>
    <mat-error>
      {{ getError('category') }}
    </mat-error>
  </mat-form-field>

.ts

compareIds(category1: ICategory, category2: ICategory): boolean {
    return category1 && category2 ? category1.id === category2.id : category1 === category2;
}