在Angular 2+中,使用mat-select和mat-option创建下拉框和选项,可以通过以下代码实现单击mat-select后显示mat-option的值:
HTML代码:
{{ option.viewValue }}
You have selected: {{selectedValue}}
Angular TypeScript代码:
options = [
{ value: '1', viewValue: 'Option 1' },
{ value: '2', viewValue: 'Option 2' },
{ value: '3', viewValue: 'Option 3' }
];
selectedValue: string;
showValues() {
this.selectedValue = null;
}
optionSelected(event) {
this.selectedValue = event.target.value;
}
在HTML文件中,使用mat-select创建下拉框,并将(click)事件绑定到showValues函数。 showValues函数将selectedValue设置为null,因此单击mat-select时mat-option中的选项将出现。
在Angular TypeScript文件中,定义选项数组和selectedValue变量。 showValues函数将selectedValue设置为null,以便在单击mat-select后重置选项值。 optionSelected函数将所选选项的值分配给selectedValue变量并显示所选选项。通过将(optionSelected)绑定到mat-select的(matChange)事件,可以在选择选项时调用该函数。
需要注意的是,在这种方法中,单击mat-select将对缩放导致mat-select所在的div突出显示显示它的选项值(将其设置为null,以便在单击mat-select后重置选项值),而不是在单击完成后显示选项值。如果要在单击完成后显示选项值,请使用(matChange)事件,而不是(click)事件。