要实现在Angular Material Select中预选择多个值,可以使用FormControl来管理选择的值。下面是一个示例解决方案:
首先,创建一个FormControl来管理选择的值:
import { Component } from '@angular/core';
import { FormControl } from '@angular/forms';
@Component({
selector: 'app-select-example',
template: `
{{option}}
`
})
export class SelectExampleComponent {
selectedOptions = new FormControl(['Option 1', 'Option 3']);
options = ['Option 1', 'Option 2', 'Option 3', 'Option 4'];
}
在上面的示例中,selectedOptions
是一个FormControl,初始值为预选的值。options
是可选的选项列表。
在模板中,将selectedOptions
绑定到mat-select的formControl
属性上,并使用ngFor循环遍历选项列表。对于每个选项,将value属性设置为选项本身,并在选项标签中显示选项的文本。
这样,选项列表中的预选择值将会在页面加载时自动被选中。
请注意,为了使用FormControl,我们需要在组件中引入FormControl
类,并在组件的构造函数中实例化FormControl对象。
希望以上解决方案可以帮助到你!