Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/angular/32.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Angular 选择角度5中的默认选项_Angular - Fatal编程技术网

Angular 选择角度5中的默认选项

Angular 选择角度5中的默认选项,angular,Angular,我正在尝试使用一个简单的选择下拉菜单,它应该有一个默认选项被选中。我尝试使用ngValue,selected,[selected]=“true”,但都不起作用 <select class="form-control" [(ngModel)]="keyType"> <option [ngValue]="'Numeric'" selected>Numeric</option> <option [ngValue]="'Random'">Random

我正在尝试使用一个简单的选择下拉菜单,它应该有一个默认选项被选中。我尝试使用ngValue,selected,[selected]=“true”,但都不起作用

<select class="form-control" [(ngModel)]="keyType"> 
<option [ngValue]="'Numeric'" selected>Numeric</option>
  <option [ngValue]="'Random'">Random</option>
</select>

数字的
随机的
它最初显示为空白,但当我选择任何选项时,就不再有空白选项了。我无法在TS端进行更改,因为keytype始终为“”,除非满足特定条件

Stackblitz链接:

您必须将
ngModel
的值设置为要选择的相应选项


空白值需要作为选项显式写入,否则一旦选择值,它们就会消失。这不是角度,这是HTML标准

尝试像这样使用绑定,不需要选择和设置值

import { Component, OnInit } from '@angular/core';

@Component({
selector: 'my-app',
templateUrl: './app.component.html',
styleUrls: [ './app.component.css' ]
})
export class AppComponent implements OnInit  {
    keyType: any;
    items = ['Numeric', 'Random']

    ngOnInit(){
        this.keyType = this.items[0];
    }
}
对于html

<select class="form-control" [(ngModel)]="keyType">
<option *ngFor="let i of items" [value]="i">{{i}}</option>  
</select>

{{keyType}}

{{i}
{{keyType}}
一种方法是提供带有空值的默认选项


这是修改后的stackblitz:

谢谢,但我不能在TS端这样做,因为对象在渲染时是不同的。对不起什么?对不起。select下拉列表使用大量ngif语句初始化,并且keytype始终设置为“”。只有在显示当前下拉列表的ngif语句中,我才想将keytype设置为numeric,否则我必须将其保留为空。然后根据您的条件设置select的值,问题是什么?在html中提供空选项是否会对您的需求造成任何问题@AmpatiHareesh,没有,但我看不出这样做的意义。最初它显示为空,因为keyType中没有任何值,在选择之后,keyType等于Numeric/Random。在这里,您不提供空值,因此keyType转到“”,这就是在选择之后无法看到空值的原因selection@Aijaz