【问题标题】:Angular Material mat-select not load the initial valueAngular Material mat-select 不加载初始值
【发布时间】:2018-09-25 02:21:55
【问题描述】:

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

可以正常工作的 HTML 选择:

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

Angular 材质组件无法按预期工作:

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

当使用简单的选择元素时,我发现我的函数 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:

我做错了什么?谢谢!

【问题讨论】:

    标签: angular6 angular-material-6


    【解决方案1】:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2020-12-05
      • 1970-01-01
      • 2019-11-29
      • 2018-10-14
      • 1970-01-01
      • 1970-01-01
      • 2018-05-17
      相关资源
      最近更新 更多