选择标签在angular8中不显示默认选项

时间:2019-06-05 15:42:28

标签: angular typescript

如果我只是这样使用:

<div style="text-align:center">
  <form>
    <select
      type="checkbox"
      name="vehicle1"
      (change)="onchange()"
    >
      <option>
        1
      </option>
      <option>
        2
      </option>
    </select>
  </form>
</div>

进展顺利,选择将默认选择第一个选项。但是如果我这样做:

<div style="text-align:center">
  <form>
    <select
      type="checkbox"
      name="vehicle1"
      [(ngModel)]="selectValue"
      (change)="onchange()"
    >
      <option [ngValue]="1">
        1
      </option>
      <option [ngValue]="2">
        2
      </option>
    </select>
  </form>
</div>

export class AppComponent {
  title = "CodeSandbox";

  public selectValue = "1";

  constructor() {}

  onchange() {
    console.log("onchange");
    console.log(this.selectValue);
  }
}

添加ngmodel和ngValue,默认情况下,select标记将显示为空。

我知道有一种添加此行以显示下拉标题的方法: <option [ngValue]="'none'" disabled>Select SortType</option>

但是我不想要,我希望它默认显示第一个选项。 有没有办法做到这一点?

this is my sample code

1 个答案:

答案 0 :(得分:1)

在使用[ngValue]时,您将其设置为number而不是string的类型

将其更改为[ngValue]="'1'"或更改public selectValue = 1;

相关问题