要获取mat-option的可见文本,您可以使用MatOption的value属性。要获取选中选项的可见文本,您可以使用MatSelect的value属性。
以下是一个示例代码,演示如何获取mat-option和选中选项的可见文本:
HTML模板:
Select an option
{{ option.label }}
组件代码:
import { Component } from '@angular/core';
@Component({
selector: 'app-my-component',
templateUrl: './my-component.component.html',
styleUrls: ['./my-component.component.css']
})
export class MyComponent {
options = [
{ value: 'option1', label: 'Option 1' },
{ value: 'option2', label: 'Option 2' },
{ value: 'option3', label: 'Option 3' }
];
getSelectedOption(select: any) {
const selectedOption = this.options.find(option => option.value === select.value);
console.log('Selected option:', selectedOption.label);
}
}
在这个示例中,我们使用*ngFor
指令来循环遍历options
数组,并将每个选项的值绑定到value
属性上。然后,我们使用{{ option.label }}
将可见文本显示在mat-option中。
在组件代码中,我们定义了一个options
数组,其中包含每个选项的值和可见文本。在getSelectedOption
方法中,我们使用find
方法查找选中选项的可见文本,并在控制台中打印出来。
当您选择一个选项并点击"Get Selected Option"按钮时,您将看到选中选项的可见文本在控制台中输出。
希望这个示例能帮助到您!