簡體   English   中英

Angular 4-反應形式-從列表中未引用的對象中選擇列表中的項目-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加載的。 但是,由於trackby,我的列表元素和對象Level的匹配得以完成。 因此,當我的對象級別被加載時,該元素在列表中被選中。

現在,我嘗試使用反應式表單轉換此代碼。 在我的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;
}

但是,舉止卻有所不同。 當我使用對象“級別”設置控件的值時,未選擇列表中具有相同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.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值進行比較。 那會拋出一個錯誤。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM