我有以下模板
<select [(ngModel)] = "selectedLocation">
<option *ngFor="let location of allLocationNames" [ngValue]="location">{{location.name}}</option>
</select>该组件具有以下ngOnInit
export class TestComponent implements OnInit {
@Input() public guest: Guest;
public allLocationNames: Location[] = []
public selectedLocation: Location;
constructor(private apiService: ApiService) {
}
ngOnInit() {
this.allLocationNames = this.apiService.allLocationNames;
this.selectedLocation = this.guest.location;
}
}我希望默认选择的元素是在组件加载时在this.selectedLocation中设置的元素。现在,下拉列表中的选定元素似乎是一个空白条目。
我在Angular 5号
发布于 2017-11-10 01:25:47
您的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中拥有了整个对象。
发布于 2019-03-12 03:07:51
检查一次...
<option value="undefined" disabled selected hidden>select</option>
<option *ngFor="let example2 of example2s" value="{{example2.value}}">{{example.exampleName}}</option>
</select>谢谢。
发布于 2017-11-08 22:14:31
您需要绑定到option元素的selected属性。只需在您的options元素中使用selected= "location === selectedLocation“,您就可以使用它了。
<option *ngFor="let location of arrayList" [selected]="location === selectedItem" >{{location.name}}</option>https://stackoverflow.com/questions/47181362
复制相似问题