首页 文章

Angular Material mat-select不加载初始值

提问于
浏览
1

我遇到了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

    我刚刚意识到我正在使用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;
    }
    

相关问题