Angular 角度选择默认选定的选择元素

Angular 角度选择默认选定的选择元素,angular,Angular,我有以下模板 <select [(ngModel)] = "selectedLocation"> <option *ngFor="let location of allLocationNames" [ngValue]="location">{{location.name}}</option> </select> 我希望默认选择的元素是加载组件时在this.selectedLocation中设置的元素。现在,下拉列表中的选定元素似

我有以下模板

  <select  [(ngModel)] = "selectedLocation">
    <option *ngFor="let location of allLocationNames" [ngValue]="location">{{location.name}}</option>
  </select>
我希望默认选择的元素是加载组件时在
this.selectedLocation
中设置的元素。现在,下拉列表中的选定元素似乎是一个空白条目


我在Angular 5上

您需要绑定到option元素的选定属性。 只需在选项元素中使用[selected]=“location===selectedLocation”,就可以了

<option *ngFor="let location of arrayList" [selected]="location === selectedItem" >{{location.name}}</option>
{{location.name}

您的
guest.location
是一个字符串,而每个位置都是一个对象。在本例中,如果您希望捕获整个对象,即使用
[ngValue]=“location”
,则需要比较在
guest.location
中获得的字符串值,并将匹配的对象分配给
selectedLocation
,而不是仅在那里有字符串值

因此,可以这样做:

ngOnInit(){
this.allLocationNames=this.apiService.allLocationNames;
this.selectedLocation=
this.allLocationNames.find(x=>x.name==this.guest.location)
}
现在,您的
selectedLocation
中有了整个对象

检查一次

    <option value="undefined" disabled selected hidden>select</option>
    <option *ngFor="let example2 of example2s" value="{{example2.value}}">{{example.exampleName}}</option>
</select>
选择
{{example.exampleName}}

谢谢。

这是Angular的预期行为,它不知道默认情况下selectedLocation的值是多少,您应该在开始时给出默认值!我看到您的
位置
对象具有
名称
属性。他们是否有
id
属性?您可以绑定到该属性,而不是绑定到对象本身(例如
[ngValue]=“location.id”
[(ngModel)]=“selectedLocationId”
)。如果您确定名称是唯一的,也可以绑定到该名称。请在使用该名称之前,先初始化此。selectedLocation,您将其用作typescript中双向绑定的ngModel!因为如果您还没有初始化它,Angular不知道在下拉列表中显示什么作为第一个属性!我相信我确实在ngOnInit()中初始化了它?请发布您的完整代码,因为只有当下拉列表首先显示空项时,才不会初始化ngModel属性。我尝试过这样做。所选的仍然是空的。我确实像以前一样在下拉列表中获得了正确的元素列表。set[ngValue]=“location.name”与以前的状态相同您是否有意添加ngModel和ngValue,因为我的ngModel和ngValue在没有它们的情况下运行良好。否则,我该如何获得双向绑定并将所选值作为对象?看见
    <option value="undefined" disabled selected hidden>select</option>
    <option *ngFor="let example2 of example2s" value="{{example2.value}}">{{example.exampleName}}</option>
</select>