Angular select默认选择select元素

时间:2017-11-08 13:47:09

标签: angular

我有以下模板

  <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上

3 个答案:

答案 0 :(得分:0)

您的guest.location是一个字符串,而每个位置都是一个对象。如果您在这种情况下想要捕获整个对象,即使用[ngValue]="location",您想要比较您在guest.location中获得的字符串值并将匹配的对象分配给您的{ {1}},而不仅仅是在那里有一个字符串值。

所以可以这样做:

selectedLocation

现在你的ngOnInit() { this.allLocationNames = this.apiService.allLocationNames; this.selectedLocation = this.allLocationNames.find(x => x.name === this.guest.location) } 已经有了整个对象。

<强> DEMO

答案 1 :(得分:0)

检查一次...

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

谢谢。

答案 2 :(得分:-1)

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

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