I have a situation where I’ve created an ion-radio, ion-input and ion-select inside a custom component. I’m using ControlValueAccessor to get values of these from my custom component. I’m getting values from ion-input fine but its not working for ion-radio and ion-select.
ion-select and ion-radio value is setting up fine as if i output it inside my custom component but not inside ngmodel of page.ts
Here is the example plunkr I’m using to get values https://embed.plnkr.co/nqKUSPWb6w5QXr8a0wEu/?show=preview
This is my code
**page.html**
<question-label [(ngModel)]="response[html.key]" ngDefaultControl style="width:100%;" item-content *ngIf="html.group == 'question_label'" [object]="html"></question-label>
**question-label.html**
<ion-input *ngIf="object.question.type == 'input' || object.question.type == 'textarea'" [(ngModel)]="value" (blur)="onBlur()" type="text" placeholder="{{object.text}}"></ion-input>
<ion-list *ngIf="object.question.type == 'radio'" [(ngModel)]="value" radio-group>
<ion-list-header>{{object.text}}</ion-list-header>
<ion-item *ngFor="let radio of object.question.responses">
<ion-label>{{radio.text}}</ion-label>
<ion-radio value="{{radio.text}}"></ion-radio>
</ion-item>
</ion-list>
<ion-item *ngIf="object.question.type == 'organization'">
<ion-label>{{object.text}}</ion-label>
<ion-select [(ngModel)]="value">
<ion-option disabled ="{{radio.disabled}}" *ngFor="let radio of object.question.responses" value="{{radio.text}}">{{radio.text}}</ion-option>
</ion-select>
</ion-item>
**question-label.ts**
import { Component, Input, forwardRef} from '@angular/core';
import { NG_VALUE_ACCESSOR, ControlValueAccessor } from '@angular/forms';
const noop = () => {
};
export const CUSTOM_INPUT_CONTROL_VALUE_ACCESSOR: any = {
provide: NG_VALUE_ACCESSOR,
useExisting: forwardRef(() => QuestionLabel),
multi: true
};
/**
* Generated class for the QuestionLabel component.
*
* See https://angular.io/docs/ts/latest/api/core/index/ComponentMetadata-class.html
* for more info on Angular Components.
*/
@Component({
selector: 'question-label',
templateUrl: 'question-label.html'
})
export class QuestionLabel implements ControlValueAccessor {
@Input() object: Object;
private innerValue: any = '';
constructor() {
}
private onTouchedCallback: () => void = noop;
private onChangeCallback: (_: any) => void = noop;
get value(): any {
return this.innerValue;
};
set value(v: any) {
if (v !== this.innerValue) {
this.innerValue = v;
this.onChangeCallback(v);
}
}
onBlur() {
this.onTouchedCallback();
}
writeValue(value: any) {
if (value !== this.innerValue) {
this.innerValue = value;
}
}
registerOnChange(fn: any) {
this.onChangeCallback = fn;
}
registerOnTouched(fn: any) {
this.onTouchedCallback = fn;
}
}