如何使用 ngFor select 第一个选项?

How to select the first option using ngFor?

我正在尝试 select 用户输入电子邮件后的第一个选项,但未 selected。 有什么解决办法吗?

image here

HTML:

<label for="login"><b>Usuário:</b></label>
                <input type="email" id="login" name="login" ngModel class="form-control" placeholder="E-mail"
                    required autofocus (focusout)="onSelect()">

 <label><b>Empresa:</b></label>
                <select ngModel name="IdEmpresa" class="form-control" id="IdEmpresa" disabled="{{ disabled }}">
                    <option *ngFor="let empresa of empresas; index as i" value="{{empresa.id}}"
                    >{{ empresa.nome }}</option>
                </select>

TS:

onSelect() {
if ($("#login").val()== null || $("#login").val() =="") {

} else {
  this.erro = false;
  this.alertService.clear();

  let email = (document.getElementById("login") as HTMLInputElement).value;
  localStorage.setItem(constants.emailSafeguard, email);

  this.service.getEmpresas(email).subscribe(lista => {
    this.empresas = lista;

    if(lista.length > 1) {
      this.disabled = false;
    } else {
      this.disabled = true;
    }
  })
}

}

你的select没有价值。请改成这样:

<select [(ngModel)]="selectedEmpresaId" name="IdEmpresa" class="form-control" id="IdEmpresa" [disabled]="disabled">
                    <option *ngFor="let empresa of empresas; index as i" [value]="empresa.id"
                    >{{ empresa.nome }}</option>
                </select>

并在 ts(初始)

this.selectedEmpresaId = this.empresas[0].id;

或者用对象代替 id

<select [(ngModel)]="selectedEmpresa" name="IdEmpresa" class="form-control" id="IdEmpresa" [disabled]="disabled">
                    <option *ngFor="let empresa of empresas; index as i" [value]="empresa"
                    >{{ empresa.nome }}</option>
                </select>

并在 ts(初始)

this.selectedEmpresa = this.empresas[0];