如何使用*ngFor获取Angular Material mat-select选中项的value和text
问题原因
你当前代码的核心问题是mat-option的[value]绑定错误,你绑定了week.text(展示文本),而非选项对应的week.value字段,导致选中后拿到的event.value是展示文本而非你需要的序号值。
修改步骤
- 调整component.html代码
把mat-option的[value]属性从week.text改为week.value即可,修改后的完整代码如下:
<mat-form-field class="week" appearance="outline"> <mat-select [(value)]="EndsofMonth" (selectionChange)="selectedValue($event)" > <mat-option *ngFor="let week of endsofmonth" [value]="week.value" > {{ week.text}} </mat-option> </mat-select> </mat-form-field> selected cycle {{ selectedData.value}} - {{ selectedData.text }}
- 调整component.ts的默认值(保证初始选中状态和展示内容匹配)
你原来的EndsofMonth默认值是文本,现在value绑定的是week.value,所以默认值要改成对应选项的value值'1st':
// 修改默认值 EndsofMonth = '1st'; selectedData: { value: string; text: string } = { value: '1st', text: 'Last day of the month ' }; selectedValue(event: MatSelectChange) { this.selectedData = { value: event.value, text: event.source.triggerValue }; console.log(this.selectedData); } // endsofmonth数组不需要修改,保持原有内容即可 endsofmonth = [ { value: '2nd', text: '1st of the month' }, { value: '3rd', text: '2nd of the month' }, { value: '4th', text: '3rd of the month' }, { value: '5th', text: '4th of the month' }, { value: '6th', text: '5th of the month' }, { value: '7th', text: '6th of the month' }, { value: '8th', text: '7th of the month' }, { value: '9th', text: '8th of the month' }, { value: '10th', text: '9th of the month' }, { value: '11th', text: '10th of the month' }, { value: '12th', text: '11th of the month' }, { value: '13th', text: '12th of the month' }, { value: '14th', text: '13th of the month' }, { value: '15th', text: '14th of the month' }, { value: '16th', text: '15th of the month' }, { value: '17th', text: '16th of the month' }, { value: '18th', text: '17th of the month' }, { value: '19th', text: '18th of the month' }, { value: '20th', text: '19th of the month' }, { value: '21st', text: '20th of the month' }, { value: '22nd', text: '21st of the month' }, { value: '23rd', text: '22nd of the month' }, { value: '24th', text: '23rd of the month' }, { value: '25th', text: '24th of the month' }, { value: '26th', text: '25th of the month' }, { value: '27th', text: '26th of the month' }, { value: '28th', text: '27th of the month' }, { value: '29th', text: '28th of the month' }, { value: '30th', text: '29th of the month' }, { value: '31st', text: '30th of the month' }, { value: '1st', text: 'Last day of the month' }, ];
效果验证
修改后选中30th of the month选项时,selectedData.value会拿到对应选项的31st,selectedData.text拿到30th of the month,刚好输出你需要的selected cycle 31st - 30th of the month。
内容的提问来源于stack exchange,提问作者Mohamed Irshath
相关产品推荐
相关产品推荐

