我需要实现一个下拉列表控件,其中包含要在我的angular 7应用程序中选择的复选框列表。有人可以告诉我他们是否使用过类似的控制方法。请注意,列表内容将是动态的
HTML
<app-checkboxes [values]="Currencies" [(ngModel)]="f.OtherCurrencyName"></app-checkboxes>
JSON
"Currencies": [
{
"Id": 7,
"Name": "AUD"
},
{
"Id": 10,
"Name": "BND"
},
{
"Id": 19,
"Name": "BRL"
},
{
"Id": 6,
"Name": "CAD"
},
{
"Id": 5,
"Name": "CHF"
},
{
"Id": 13,
"Name": "CNH"
},
{
"Id": 12,
"Name": "CNY"
},
{
"Id": 18,
"Name": "DKK"
}]
答案 0 :(得分:0)
我建议创建一个实现ControlValueAccessor
的自定义组件:
@Component({
selector: 'app-checkboxes',
templateUrl: './checkboxes.component.html',
styleUrls: ['./checkboxes.component.css'],
providers: [
{
provide: NG_VALUE_ACCESSOR,
useExisting: forwardRef(() => CheckboxesComponent),
multi: true
}
]
})
export class CheckboxesComponent implements ControlValueAccessor {
@Input() values: string[] = [];
selectedValues = {};
onChange = (value: any) => { };
onTouched = () => { };
writeValue(initValue: any): void {
this.selectedValues = initValue || {};
}
registerOnChange(fn: any): void {
this.onChange = fn;
}
registerOnTouched(fn: any): void {
this.onTouched = fn;
}
}