I have a simple custom radio button control. HTML:
<label class="radiobutton-container" >
<ng-content></ng-content>
<input type="radio" [value]="value" [name]="name" [disabled]="disabled" (change)="handleChange($event)" [checked]="checked"/>
<span [ngClass]="{'checkbase': true,
'checkmark' : checked
}"></span>
</label>
In general it works fine, I can tell if it is checked and put it into groups, etc. But - when I use it in a form, I just the value of the group as "true" instead of the value of the component:
<form #form="ngForm" >
<my-radiobutton [ngModel]="mymodel" [name]="'options'" [value]="'value1'" >Value 1</my-radiobutton>
<my-radiobutton [ngModel]="mymodel" [name]="'options'" [value]="'value2'" >Value 2</my-radiobutton>
<my-radiobutton [ngModel]="mymodel" [name]="'options'" [value]="'value3'" >Value 3</my-radiobutton>
</form>
<p>form value:</p>
<pre>{{ form.value | json }}</pre>
When I print the value of the form, it is just "options: true", instead of "value1", "value2", etc.
Not sure what I am doing wrong. Any help appreciated!
Use array instead of calling the component again and again, Please refer the below code App.component.html
`<form>
<app-my-radiobutton [inputList]="radioList"
(changedInput)="onValueChange($event)"></app-my-radiobutton>
</form>
<pre *ngIf="title">
{{title.form.value | json}}
</pre>`
App.component.ts
title: NgForm;
radioList = ['Male', 'Female'];
onValueChange(event) {
this.title = event
}
Myradiobutton.Component
@Input() inputList = [];
@Output() changedInput = new EventEmitter<any>();
inputData: string;
constructor() { }
ngOnInit() {}
onChange(event, form) {
this.changedInput.emit(form)
}
Myradiobutton.HTML
`<div class="container">
<form #form="ngForm">
<div *ngFor="let item of inputList; let i = index">
<input type="radio" id="{{item+i}}" name="gender" value="{{item}}"
[(ngModel)]="item" (change)="onChange($event, form)">
<label for="male">{{item}}</label><br>
</div>
</form>
</div>`
Output
{ "gender": "Male" } or { "gender": "FeMale" }