import { Component, Input, forwardRef, OnInit, EventEmitter, Optional, Injector } from '@angular/core'; import { NG_VALUE_ACCESSOR, ControlValueAccessor, RadioControlValueAccessor } from '@angular/forms'; import { IdService, CommonUtils } from '@farris/ui-common'; import { Radio } from './radio'; import { Output } from '@angular/core'; @Component({ selector: 'farris-radiogroup', templateUrl: './radiogroup.component.html', providers: [{ provide: NG_VALUE_ACCESSOR, useExisting: forwardRef(() => FarrisRadioGroupComponent), multi: true, }], exportAs: 'FarrisRadioGroupComponent' }) export class FarrisRadioGroupComponent implements ControlValueAccessor, OnInit { @Input('tab-index') tabIndex: number; /* radio 数组 */ @Input() data: Radio[] = []; /* radio 类型 原生或者按钮类型*/ @Input() type: string; /* name标识 */ @Input() name: string; /* 水平排列 */ @Input() horizontal: boolean; /* 禁用 */ @Input() disabled: boolean; /* radio 值 */ @Input() value: any; @Input() textField = 'name'; @Input() valueField = 'value'; /* 点击事件 */ @Output() changeValue = new EventEmitter(); private commonUtils: CommonUtils; constructor(private idSer: IdService, @Optional() private inject: Injector) { if (this.inject) { this.commonUtils = this.inject.get(CommonUtils); } } ngOnInit() { this.name = this.idSer.generate().replace(/-/g, '_'); } clickHandler(item: any) { let val = this._getValue(item); if(this.value == val) return; // 更改control的值 this.value = val; this.controlChange(this.value); this.controlTouch(this.value); this.changeValue.emit(this.value); } _getText(item) { if (item) { if (this.commonUtils && this.commonUtils.getValue) { return this.commonUtils.getValue(this.textField, item); } else { return item[this.textField]; } } else { return ''; } } _getValue(item) { if (item) { if (this.commonUtils && this.commonUtils.getValue) { return this.commonUtils.getValue(this.valueField, item); } else { return item[this.valueField]; } } else { return ''; } } writeValue(value: any): void { this.value = value; } registerOnChange(fn: () => void): void { this.controlChange = fn; } registerOnTouched(fn: () => void): void { this.controlTouch = fn; } private controlChange: (value: any) => void = () => { }; private controlTouch: (value: any) => void = () => { }; }