在我的角度6项目中,我有mat-select,我必须使用 compareWith
函数,因为我正在选择对象 .
但是目前如果我没有手动设置字段中的任何值,我看到比较函数正在比较第一个选项......我不想要这种行为 . 表单在此字段中仍然具有 null
值 .
这是预期的行为还是我遗漏了什么?
附:我无法在我的选项中添加像_2683981这样的选项 .
html
<mat-form-field>
<mat-select (selectionChange)="fareExceptionHandler(); setFareExceptionCode($event)" formControlName="fareException" [compareWith]="displayFn"
placeholder="{{'ticket.new.labels.fareexception' | translate }}" name="fare">
<mat-option *ngFor="let fare of fareExceptionsList" [value]="fare">
{{ fare.name }} </mat-option>
</mat-select>
</mat-form-field>
compare function
displayFn(model: any) {
if ((model !== undefined) && (model !== null)) {
return model.name;
}
}
*********************************************编辑 *****************************************
这是一个类似的例子https://stackblitz.com/edit/angular-rykism?file=app%2Fselect-overview-example.ts
1 回答
你的
compareWith
功能错了 . 您正在使用它像Autocomplete的displayWith
函数,但它不能那样工作 . 它需要两个参数并返回boolean
值 . 它's main purpose is to find matching options from values applied externally, which happens automatically on initialization, and if you use a form control, the form control'的值用于初始化选择值 .当参数对象相等时,默认实现返回true . 您的实现返回第一个参数对象
name
,它是一个选项 . 这是真实的,因此您的函数在初始化时最终匹配列表中的第一个选项 . 第二个参数是传入"set"值,初始化时为undefined
(除非您的表单控件具有值) .因此,您的函数基本上是说
undefined
与第一个选项匹配,因此列表在启动时选择第一个选项 . 您可能根本不需要使用compareWith
,所以只需要摆脱它 .