在select中设置默认选项

时间:2017-07-07 05:40:40

标签: forms select angular2-forms options

<form (ngSubmit)="onSubmit()" #myForm="ngForm">
            <div class="form-group">
                <select name="location" class="form-control" class="selectLocation" [(ngModel)]="nameSelectedVal" (ngModelChange)="onChange($event)">


                    <option *ngFor="let location of locations" [ngValue]="location.code" [disabled]="location.code==0">
                        {{location.city}}
                    </option>

                </select>

                <p class="selectArrow"><button  [disabled]="disableFlag" routerLink="/my-bookride" class="leftArrow">
                <span class="glyphicon glyphicon-arrow-right"></span></button></p>
            </div>
        </form>

这是我用来选择我需要显示的选项的形式当加载表格时选择一个城市作为默认选项

export class locationComponent
 {
      butDisabled: boolean = true;
    disableFlag:boolean = true;;
       private locations: any;
  constructor() {

        this.locations = [
  {
    "code": 0,
    "city": "Select one city"
  },
  {
    "code": 1,
    "city": "Hyderabad"
  },
  {
    "code": 2,
    "city": "Banglore"
  }
];
  this.nameSelectedVal = this.locations[0];
}

onChange($event) {
    if($event!=="0"){
   this.disableFlag=false;
   } else{
   this.disableFlag=true;
   }
}
}

我正在提供在HTML视图中显示的选项 我尝试使用[ngValue]将“选择一个城市”设置为默认值

1 个答案:

答案 0 :(得分:0)

使用因为它是您的HTML:   

                <option *ngFor="let location of locations" [ngValue]="location.code" [disabled]="location.code==0">
                    {{location.city}}
                </option>


            </select>

并在TS文件内分配: this.nameSelectedVal = this.locations [0] .code;

它会起作用。