Angular 默认情况下,选择第一个菜单项
我想实现选择菜单,该菜单使用枚举数据显示数据,并根据所选字符串保存数字: 我试过这个: 枚举: 组成部分:Angular 默认情况下,选择第一个菜单项,angular,typescript,angular6,Angular,Typescript,Angular6,我想实现选择菜单,该菜单使用枚举数据显示数据,并根据所选字符串保存数字: 我试过这个: 枚举: 组成部分: public MerchantStateType2LabelMapping = MerchantStateType2LabelMapping; public stateTypes = Object.values(MerchantStateType); HTML代码: <select class="custom-select" name="state_raw" [(ngModel)
public MerchantStateType2LabelMapping = MerchantStateType2LabelMapping;
public stateTypes = Object.values(MerchantStateType);
HTML代码:
<select class="custom-select" name="state_raw" [(ngModel)]="merchant.state_raw" id="state_raw" required>
<!--<option selected></option>-->
<option [value]="stateType" *ngFor="let stateType of stateTypes">{{ MerchantStateType2LabelMapping[stateType] }}</option>
{{MerchantStateType2LabelMapping[stateType]}
默认情况下如何选择第一个菜单项?您可以在ngOnInit()中添加以下内容 (或)您可以使用*ngFor的局部变量'first'
<select class="custom-select" name="state_raw" [(ngModel)]="merchant.state_raw" id="state_raw" required>
<!--<option selected></option>-->
<option [value]="stateType" *ngFor="let stateType of stateTypes; first as isFirst" [selected]="isFirst">{{ MerchantStateType2LabelMapping[stateType] }}</option>
</select>
{{MerchantStateType2LabelMapping[stateType]}
在需要ngOnInit(),Constructor()的位置设置初始值:
state_raw保存枚举的索引。
您的选择如下所示:
<select class="custom-select" name="state_raw" [(ngModel)]="marchant.state_raw" id="state_raw" required>
<option [value]="stateType" *ngFor="let stateType of stateTypes">{{ MerchantStateType2LabelMapping[stateType] }}
</option>
</select>
致:
publicstatetypes=Object.values(MerchantStateType).filter(type=>
isNumber(类型)
);
这将从值中删除id,并仅获取HTML中的字符串
<select class="custom-select" name="state_raw" [(ngModel)]="current" id="state_raw" required>
<!--<option selected></option>-->
<option [value]="stateType" *ngFor="let stateType of stateTypes">{{ MerchantStateType2LabelMapping[stateType] }}</option>
现在,选择字段的值将通过变量this.current
获得
this.merchant.state_raw = 1;
<select class="custom-select" name="state_raw" [(ngModel)]="marchant.state_raw" id="state_raw" required>
<option [value]="stateType" *ngFor="let stateType of stateTypes">{{ MerchantStateType2LabelMapping[stateType] }}
</option>
</select>
public stateTypes = Object.values(MerchantStateType);
public stateTypes = Object.values(MerchantStateType).filter(type =>
isNumber(<any>type)
);
<select class="custom-select" name="state_raw" [(ngModel)]="current" id="state_raw" required>
<!--<option selected></option>-->
<option [value]="stateType" *ngFor="let stateType of stateTypes">{{ MerchantStateType2LabelMapping[stateType] }}</option>
public current = 1;