为什么我的 html 选择没有选择数据的第一个值?



我有两个几乎相同的选择选项,一个如我预期的那样在选择框中显示选项的第一个值,但另一个不是。

这个没有像我期望的那样选择第一个值:

<div class="col-3 col-md-1 text-center">
<select name="quantity" [(ngModel)]="item.quantity">
<option *ngFor="let quantity of quantities" [value]="quantity.value">
{{quantity.value}}
</option>
</select>
</div>

上述选择框的数据:(我希望值 1 自动显示在选择框中,但事实并非如此(。

this.quantities = [
{value: 1 },
{value: 2 },
{value: 3 },
{value: 4 },
{value: 5 },
{value: 6 },
{value: 7 },
{value: 8 },
{value: 9 },
{value: 10 }
];

这个按预期显示了选择框的第一个值:

<select name="exp_year" [(ngModel)]="order.customer.payment.exp_year">
<option *ngFor="let expYear of expYears">
{{expYear.year}}
</option>
</select>

此选择的数据:(2019 年按预期显示在选择框中(:

this.expYears = [
{ year: '2019' },
{ year: '2020' },
{ year: '2021' },
{ year: '2022' },
{ year: '2023' },
{ year: '2024' },
{ year: '2025' },
{ year: '2026' },
{ year: '2027' },
{ year: '2028' },
];

您需要初始化选择框以设置默认值。堆栈闪电战演示

.ts

import { Component } from '@angular/core';
@Component({
selector: 'my-app',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
quantity = 2;
quantityList = [
{ value: 1 },
{ value: 2 },
{ value: 3 },
{ value: 4 },
{ value: 5 },
{ value: 6 },
{ value: 7 },
{ value: 8 },
{ value: 9 },
{ value: 10 }
];
}

。.html

<select name="quantity" [(ngModel)]="quantity">
<option *ngFor="let quantity of quantityList" [value]="quantity.value">
{{quantity.value}}
</option>
</select>

最新更新