可以使用 Angular 的 FormControl 和 valueChanges 方法来实现这个需求。我们需要在组件中定义一个 FormControl,并监听该 FormControl 的 valueChanges 事件。当选项选择更改时,该事件会触发,我们可以在该事件中获取选中的选项的值。
示例代码如下:
HTML 模板:
组件代码:
import { Component } from '@angular/core';
import { FormControl } from '@angular/forms';
@Component({
selector: 'app-example',
templateUrl: './example.component.html',
styleUrls: ['./example.component.css']
})
export class ExampleComponent {
selectedOption = new FormControl();
options = [
{ label: 'Option 1', value: 'option-1' },
{ label: 'Option 2', value: 'option-2' },
{ label: 'Option 3', value: 'option-3' }
];
constructor() {
this.selectedOption.valueChanges.subscribe((value) => {
console.log(value); // 输出选中的选项的值
});
}
}