我正在创建一个带有单选按钮的组件,在以反应形式使用此组件时,我需要设置和获取其值。我还需要能够选择默认收音机。解决此问题的最佳方法是什么?
我的 radio-button.component.html :
<ion-list>
<ion-radio-group *ngIf="orientation === 'horizontal'">
<ion-row>
<ion-col *ngFor="let options of items">
<ion-item lines="none">
<ion-label>{{ options.value }}</ion-label>
<ion-radio
mode="md"
slot="start"
[value]="options.id"
(click)="selectOption(options)"
[disabled]="formControlRadio.disabled"
></ion-radio>
</ion-item>
</ion-col>
</ion-row>
</ion-radio-group>
</ion-list>
单选按钮.component.ts:
import { Component, Input, forwardRef, OnInit } from '@angular/core';
import { ControlValueAccessor, NG_VALUE_ACCESSOR, FormControl } from '@angular/forms';
import { Orientation } from "../enums";
const TYPE_CONTROL_ACCESSOR = {
provide: NG_VALUE_ACCESSOR,
useExisting: forwardRef(() => RadioButtonComponent),
multi: true
};
@Component({
selector: 'comp-radio-button',
templateUrl: './radio-button.component.html',
styleUrls: ['./radio-button.component.scss'],
providers: [TYPE_CONTROL_ACCESSOR]
})
export class RadioButtonComponent implements OnInit, ControlValueAccessor {
@Input() items = [{}];
@Input() orientation = Orientation.Horizontal;
@Input() formControlRadio: FormControl;
constructor() { }
ngOnInit() {
}
onChange: Function = () => { }
onTouch: Function = () => { }
value = '';
// this method sets the value programmatically
writeValue(obj: string) {
this.value = obj;
}
// upon UI element value changes, this method gets triggered
registerOnChange(fn: Function) {
this.onChange = fn;
}
// upon touching the element, this method gets triggered
registerOnTouched(fn: Function) {
this.onTouch = fn;
}
selectOption(value: string) {
this.value = value;
this.onChange(value);
this.onTouch();
return this.value;
}
}
app.component.html:
<some form>
<comp-radio-button
name="radioBtn"
[items]="radioItems"
orientation="horizontal"
formControlName="radio"
[formControlRadio]="formControlRadioInput">
</comp-radio-button>
app.component.ts:
formControlRadioInput: FormControl;
radioItems = [
{ value: 'Option 1', id: 'op1' },
{ value: 'Option 2', id: 'op2' },
{ value: 'Option 3', id: 'op3' },
{ value: 'Option 4', id: 'op4' }
]
我需要能够在这些方面做一些事情:
constructor(){
this.formControlRadioInput = new FormControl({ value: 'op1', disabled: false }, [Validators.required]);
}
OR
this.formControlRadioInput.setValue('op1')