在选择下拉列表-角度中显示默认选择

时间:2018-11-11 10:18:17

标签: javascript angular typescript

这是我的代码:

<select label="people" id="ppl"  [(ngModel)]="Selectedppl" (ngModelChange)="onPplSelection($event.target.value)">
<option>select people</option>
<option *ngFor="let x of peopleList" [ngValue]="x">
    {{x.name}}
</option>

由于人员列表是带有名称,地址和联系人的对象。我想使用ngValue将对象作为参数发送给ngModelChange。

但是,一旦我选择了一个特定的人并保存了,我希望将下拉列表更改为选定的人名。基本上我想 保存后,在下拉列表中显示默认的选定选项。

我不使用Reactiveforms。

1 个答案:

答案 0 :(得分:0)

  

您可以获取element的引用并将其值传递给函数。

<select label="people" id="ppl" #ppl="ngModel"  
   [(ngModel)]="Selectedppl" 
   [compareWith]="compareFn"
   (ngModelChange)="onPplSelection(ppl.value)">
     <option>select people</option>
     <option *ngFor="let x of peopleList" [ngValue]="x">
       {{x.name}}
     </option>
</select>

ts

如果您有复杂的对象,则必须使用compareFn,它可以帮助Angular比较对象以设置默认值。

  compareFn(a, b) {
    if (!a || !b) {
      return false;
    } else {
      return a.name === b.name;
    }
  }

工作副本在这里-https://stackblitz.com/edit/hello-angular-6-2z9f3b

相关问题