以下是使用formControlName和ControlValueAccessor的Angular 8的Mat-Select列表下拉菜单的解决方法。
首先,在你的组件的HTML模板中,使用formControlName指令来绑定一个FormControl对象到Mat-Select元素上。同时,使用[(ngModel)]指令来将FormControl的值与组件的属性进行双向绑定。
接下来,在你的组件的TypeScript文件中,实现ControlValueAccessor接口来自定义一个表单控件的值访问器。
import { Component, forwardRef } from '@angular/core';
import { ControlValueAccessor, NG_VALUE_ACCESSOR } from '@angular/forms';
@Component({
selector: 'app-my-component',
templateUrl: './my-component.component.html',
styleUrls: ['./my-component.component.css'],
providers: [
{
provide: NG_VALUE_ACCESSOR,
useExisting: forwardRef(() => MyComponentComponent),
multi: true
}
]
})
export class MyComponentComponent implements ControlValueAccessor {
selectedValue: string;
options = [
{ value: 'option1', label: 'Option 1' },
{ value: 'option2', label: 'Option 2' },
{ value: 'option3', label: 'Option 3' }
];
onChange: any = () => {};
onTouch: any = () => {};
writeValue(value: any) {
this.selectedValue = value;
}
registerOnChange(fn: any) {
this.onChange = fn;
}
registerOnTouched(fn: any) {
this.onTouch = fn;
}
setDisabledState(isDisabled: boolean) {}
updateValue(value: string) {
this.selectedValue = value;
this.onChange(value);
this.onTouch();
}
}
在上面的代码中,我们实现了ControlValueAccessor接口的所有方法,包括writeValue、registerOnChange、registerOnTouched和setDisabledState。其中,writeValue方法用于将FormControl的值传递给组件的属性,registerOnChange方法用于注册一个回调函数,当FormControl的值发生变化时触发,registerOnTouched方法用于注册一个回调函数,当FormControl被触摸时触发,setDisabledState方法用于禁用或启用表单控件。
最后,在你的模块文件中,记得导入FormsModule和ReactiveFormsModule。
import { FormsModule, ReactiveFormsModule } from '@angular/forms';
@NgModule({
imports: [
FormsModule,
ReactiveFormsModule,
// other imports
],
// other configurations
})
export class AppModule { }
现在,你就可以使用formControlName和ControlValueAccessor来实现一个带有Mat-Select的下拉菜单,并且能够与FormControl进行双向绑定了。