Angular 4 - 响应式表单 - select 列表中的项目来自未在此列表中引用的对象 - trackby 问题?

Angular 4 - Reactive Forms - select item in a list from object not referenced in this list - trackby issue?

我正在将 Angular 1.6 代码转换为 Angular 4,我对元素列表有疑问。 Angular 1.6 中的代码是:

<select ng-model="$ctrl.level" ng-options="item as item.label for item in $ctrl.referentiel.levels | orderBy : 'index' track by item.id"                                   id="childLevel" name="childLevel" class="size-xl"                               >
<option value="">Select</option>
</select>

我的列表中未引用对象级别,因为此列表是使用对象 referentiel.levels 加载的。但是我的列表元素和我的对象 Level 之间的匹配是通过 trackby 完成的。因此,当加载我的对象 Level 时,该元素会在列表中被选中。

现在,我尝试使用 Reactive Forms 转换这段代码。 在我的 HTML 代码中,我有:

<select formControlName="levelControl" id="levelSelect" name="levelSelect" class="size-xl">
<option [ngValue]="null">Select</option>
<option *ngFor="let level of referentiel.levels;trackBy:identify" [ngValue]="level">{{level.label }}</option>
</select>

在我的组件中,我在 OnInit 方法中有:

(<FormControl>this.myForm.controls.levelControl).setValue(this.level);

而且识别方法很简单:

identify(index,item){
   return item.id;
}

但举止不同。当我使用我的对象 Level 设置我的控件的值时,列表中具有相同 id 的项目未被选中。

我找到了解决方案,但我不明白为什么它不起作用。 我的解决方法是在 HTML:

中编写此代码
<option *ngFor="let level of referentiel.levels;trackBy:identify" [ngValue]="level.id">{{level.label }}</option>

在我的打字稿文件中:

(<FormControl>this.myForm.controls.levelControl).setValue(this.level.id);

所以,现在它正在工作:我的项目在列表中被选中。

在这种情况下,我不明白 Angular 的两个版本之间的区别。 也许我错过了什么......

感谢您的帮助。

我看不出您需要此处的 trackBy,除非您想使用它。但这与您的默认选项不起作用的原因无关。

为什么它与 level.id 一起工作是因为这是一个字符串(数字?)而 level 是一个没有引用您的数组的对象,因此无法从列表中识别它。

由于您使用的是 Angular 4,我们现在有一个新指令 [compareWith],我们可以在其中比较您的 level 中的一些 属性,例如 id。将其与数组进行比较并找到匹配项。所以你可以做的是:

<select formControlName="levelControl" [compareWith]="compare" 
  id="levelSelect" name="levelSelect" class="size-xl">
    <option value="">Select</option>
    <option *ngFor="let level of referentiel.levels" [ngValue]="level">
      {{level.label }}
    </option>
</select>

组件:

compare(val1, val2) {
  return val1.id === val2.id;
}

另请注意,我更改了

<option [ngValue]="null">Select</option>

<option value="">Select</option>

这样 Angular 就不会尝试与 null 值进行比较。那会引发错误。