Angular默认选项选择的属性不按预期工作

时间:2017-11-29 10:21:46

标签: angular

我想从下拉列表中选择第一个选项。但是,当我将[attr.selected]="index == 1"[attr.selected]="index == 0"设置为无效时,如果我将索引值条件更改为[attr.selected]="index == 2",则可以正常工作。虽然从0到2的索引存在。

<select formControlName="segmentforOverlapOne" class="form-control overlap-segment-1">
  <option [attr.selected]="index == 1" *ngFor="let segment of segmentations; let index=index;" [ngValue]="index">{{segment.name}}</option>
</select>

以下是分段数组:

[
  {
    "name": "name 1",
    "columns": [
      {
        "index": 0,
        ...
      }
    ],
  },
  {
    "name": "name 2",
    "columns": [
      {
        "index": 1,
        ...
      }
    ],
  },
  {
    "name": "name 3",
    "columns": [
      {
        "index": 2,
        ...
      }
    ]
  }
]

5 个答案:

答案 0 :(得分:1)

尝试这样:

<select formControlName="segmentforOverlapOne" class="form-control overlap-segment-1"> 
    <option *ngFor="let segment of segmentations; let i = index" [attr.value]="i" [attr.selected]="i == 0 ? true : null">{{segment.name}}</option>
</select>

答案 1 :(得分:0)

使用三元运算返回true或null值。否则,它不会被删除。

{{1}}

答案 2 :(得分:0)

使用[attr.selected] = "(index == 1)? 'any value whatsoever' : null"

Html没有看到所选属性的值。它只能看到它是否存在。如果属性值为null,Angular将删除该属性。

答案 3 :(得分:0)

<select formControlName="segmentforOverlapOne" class="form-control overlap-segment-1" [(ngModel)]="1">

如果所选属性的空值失败,这应该有效。

答案 4 :(得分:0)

确保您使用的是[attr.value],而不是[ngvalue]

然后按照第一个答案中的建议使用它

<select formControlName="segmentforOverlapOne" class="form-control overlap-segment-1"> 
<option *ngFor="let segment of segmentations; let i = index" [attr.value]="i" 
[attr.selected]="i == 0 ? true : null">{{segment.name}}</option>
</select>