在 Angular 中设置默认值
我们将学习如何在 select 表单中设置默认值,从选项数组中设置默认值,以及如果选项在 Angular 中是动态的,则设置默认值。
在 Angular 中设置默认值
本教程将讨论如何在 Angular 中为选择标签设置默认值。创建具有多个选项的 select 表单时,不会自动选择默认值。
因此,我们将首先创建一个选择表单并设置默认值,并且我们将在选项静态或动态或有一系列选项时设置默认值的最佳方式,我们将讨论不同的方案。
在 app.component.html 中,我们将创建一个 select 表单。
# angular
<select [(ngModel)]='ngSelect' name="selectOption" id="selectOption" class='form-control'>
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
</select>
我们将在 app.component.css 中添加 CSS 以使我们的 select 表单看起来更好。
# angular
.form-control{
padding: 5px 10px;
background-color: DodgerBlue;
color: white;
border-color: black;
width: 100px;
height: 30px;
}
option:hover{
background-color: white;
color: dodgerblue;
}
输出:

你可以看到没有选择默认值,但是当我们单击它时会出现所有选项。

要将任何值设置为默认值,我们可以将值分配给 app.component.ts 中的变量 ngSelect。如果你从 app.component.html 中查看我们的代码,你可以看到我们已经分配了变量 [(ngModel)]='ngSelect'。
现在让我们尝试将 1 设置为默认值。
# angular
import { Component, VERSION } from '@angular/core';
@Component({
selector: 'my-app',
templateUrl: './app.component.html',
styleUrls: [ './app.component.css' ]
})
export class AppComponent {
ngSelect = 1;
}
指定默认值后,我们会注意到选择表单显示 1 作为当前默认值。这样,我们可以选择任何值作为 Angular 中的默认值。
输出:

从 Angular 的选项数组中设置默认值
我们将讨论从一组选项中设置默认值。
首先,我们将创建两个变量:ngSelect,我们选择表单的默认选项,第二个是 options,它将包含我们想要在选择选项中显示的所有值。
让我们将此代码添加到 app.component.ts 中。
# angular
import { Component, VERSION } from '@angular/core';
@Component({
selector: 'my-app',
templateUrl: './app.component.html',
styleUrls: [ './app.component.css' ]
})
export class AppComponent {
options = [1,2,3,4,5,6,7,8,9,10]
ngSelect = 1;
}
在 options 数组中,我们设置从 1 到 10 的值;在 ngSelect 中,我们将 1 设置为默认值。
我们将在 app.component.html 中创建选择表单。
# angular
<select class='form-control' id="selectOptions">
<option *ngFor="let opt of options"
[selected]="opt === ngSelect"
[value]="opt">
{{ opt }}
</option>
</select>
在这段代码中,你可以看到我们已经将 [selected] 设置为 ngSelect,所以当任何选项与 ngSelect 相同时,它会自动被选中。
输出:

从 Angular 的动态值中选择默认值
如果我们有选项的动态值,我们将讨论设置默认值。
首先,我们将创建两个变量:ngSelect,我们选择表单的默认选项,第二个是 options,它将包含我们想要在选择选项中显示的所有值。
我们知道会有动态值,所以让我们有一个随机数数组并为该数组中的第一项设置默认值。
# angular
import { Component, VERSION } from '@angular/core';
@Component({
selector: 'my-app',
templateUrl: './app.component.html',
styleUrls: [ './app.component.css' ]
})
export class AppComponent {
options = [3,6,1,4,2,10,7,5,9,8]
ngSelect = this.options[0];
}
app.component.html 将具有以下代码。
# angular
<select class="form-control" id="selectOptions">
<option
*ngFor="let opt of options"
[selected]="opt === ngSelect"
[value]="opt"
>
{{ opt }}
</option>
</select>
输出:

你可以看到该数组的第一项设置为默认值。我们可以通过改变数组的索引来改变它。
本教程教我们在 Angular 中为 select 表单设置默认值。我们还讨论了静态、动态或数组值的三个默认值。
Rana is a computer science graduate passionate about helping people to build and diagnose scalable web application problems and problems developers face across the full-stack.
LinkedIn