要在Angular Material的选择下拉框中发射整个对象项,而不仅仅是一个值,可以使用value
属性来设置下拉框中每个选项的值,并使用[(ngModel)]
来绑定选中的对象。
以下是一个示例代码:
HTML模板:
选择项
{{ option.name }}
组件代码:
import { Component } from '@angular/core';
@Component({
selector: 'app-example',
templateUrl: './example.component.html',
styleUrls: ['./example.component.css']
})
export class ExampleComponent {
selectedItem: any;
options = [
{ id: 1, name: '选项1' },
{ id: 2, name: '选项2' },
{ id: 3, name: '选项3' }
];
onSelectionChange(selectedOption: any) {
console.log(selectedOption);
}
}
在这个示例中,selectedItem
变量用于绑定选中的对象项,options
数组包含下拉框中的选项。当选择项发生改变时,onSelectionChange
方法会被调用,并且会传递选中的对象项作为参数。你可以在onSelectionChange
方法中进行任何你想要的操作,比如打印选中的对象项。
请注意,为了确保正确显示选中的对象项,需要使用[value]
属性来设置每个选项的值为对应的对象。在这个示例中,我们将option
对象作为整个值传递给下拉框选项的value
属性。