Angular select option with selected attribute not working

sla*_*den 9 html-select angular2-ngmodel angular

Using Angular 4, I have a html template and I want a selection box with two options. One of those options should be pre-selected by default.

<select name="rate" #rate="ngModel" ngModel required>
    <option selected value="hr">hr</option>
    <option value="yr">yr</option>
</select>
Run Code Online (Sandbox Code Playgroud)

Details:

I assign #rate="ngModel" so that I can reference the value somewhere else in the template, in a conditional statement or with interpolation {{rate.value}}. For that to work I simply add ngModel to the tag. I'm not binding to anything in the component class as this control is only used to provide it's value to another control in the same template.

Issue:

In Chrome, and Microsoft Edge, the box is empty, no default value selected. If I get rid of #rate="ngModel" ngModel it works. However, I need the reference to rate.value.

我尝试了 ngValue、value、[ngValue]、[value] 的各种组合,但我没有尝试将值绑定到模型,也没有使用 ngFor 循环。选择框上也没有进一步的样式。

Veg*_*ega 10

如果您不希望有双向绑定,可以将 ngModel 设置为“默认”值,并使用模板局部变量获取所选值:

<select #rate ngModel="hr">
    <option selected value="hr">hr</option>
    <option value="yr">yr</option>
</select>

<p *ngIf="rate.value == 'hr'">hr</p> 
<p *ngIf="rate.value == 'yr'">yr</p>

{{rate.value}}
Run Code Online (Sandbox Code Playgroud)

演示版


Cri*_*ìna 9

当您使用 ngModel 时,状态是在内部处理的,对它的任何显式更改都会被忽略。在您的示例中,您正在设置optionselected属性,但您还为您的select提供了一个(无效)ngModel ,因此 Angular 期望在 ngModel 中提供选择的状态。

简而言之,您应该利用ngModel而不是设置selected属性:

<select 
    name="rate" 
    #rate="ngModel" 
    [(ngModel)]="yourModelName" 
    required>
    <option value="hr">hr</option>
    <option value="yr">yr</option>
</select>
Run Code Online (Sandbox Code Playgroud)

和:

  yourModelName: string;
  constructor() {
    this.yourModelName = 'hr';
  }
Run Code Online (Sandbox Code Playgroud)