Ionic 3: How to get only selected value from RadioButton? - ionic-framework

I've multiple radio button in a list and I want to get only the value of selected radio button but I'm getting the value of clicked events.
Like if I click option 1 (10 times) and then select option 2 (1 time) I am getting the value like
[Option 1, Option 1,Option 1....x10time, Option 2]
How can I do this?
Below is my code.
my HTML,
<ion-list radio-group [(ngModel)]="sizeDetails">
<ion-list-header>
Select Your Preference
</ion-list-header>
<ion-item no-lines *ngFor="let list of prices_details; let i = index;">
<ion-label text-wrap style="font-size:12px; color:black;">
{{list.size}}
</ion-label>
<ion-label fixed text-right style="font-size:12px; color:black;">
{{list.discounted_price_pretty}}
</ion-label>
<ion-radio item-left color="secondary" value="{{list.size}}, {{list.discounted_price_pretty}}"
(ionSelect)="selectSize(list.size ,list.discounted_price_pretty, $event)">
</ion-radio>
my.ts code,
selectSize(size, discounted_price_pretty, event) {
if (event.checked) {
this.selectedSize.push(size);
this.selectedSizePrice.push(discounted_price_pretty);
}
else {
let sizeindex = this.removeCheckedFromSize(size);
this.selectedSize.splice(sizeindex, 1);
let sizeprice = this.removeCheckedFromSizePrice(discounted_price_pretty);
this.selectedSizePrice.splice(sizeprice, 1);
}
}
//Removes checkbox from array when user uncheck it
removeCheckedFromSize(size: String) {
return this.selectedSize.findIndex((sizeType) => {
return sizeType === size;
})
}
//Removes checkbox from array when you uncheck it
removeCheckedFromSizePrice(discounted_price_pretty: String) {
return this.selectedSizePrice.findIndex((sizeprice) => {
return sizeprice === discounted_price_pretty;
})
}

First of all, I don't think selectSize as a function needs to be that big. I would suggest you apply the Single Responsibility Principle when writing your code.
Second, in the case where this is a form, I would recommend you use Form Groups. However, if you choose to stick with your approach, which is absolutely fine, you might want your code to simply get the $event value upon submission.
The event parameter in your TS file's function will return the value parameter from the ion-radio HTML element.

Try this, this is my code for dynamic item review and it is working fine so use it as per your requirement.
<span *ngFor="let item of list_launches">
<ion-row radio-group [(ngModel)]="item.review" (ionChange)="itemReview(item.review,item.item)">
<ion-col col-4 text-wrap>
<ion-item no-padding>
{{item.item}}
</ion-item>
</ion-col>
<ion-col class="rate">
<ion-item no-padding>
<ion-radio [value]="item.value1"></ion-radio>
</ion-item>
</ion-col>
<ion-col class="rate">
<ion-item no-padding>
<ion-radio [value]="item.value2"></ion-radio>
</ion-item>
</ion-col>
<ion-col class="rate">
<ion-item no-padding>
<ion-radio [value]="item.value3"></ion-radio>
</ion-item>
</ion-col>
<ion-col class="rate">
<ion-item no-padding>
<ion-radio [value]="item.value4"></ion-radio>
</ion-item>
</ion-col>
<ion-col class="rate">
<ion-item no-padding>
<ion-radio [value]="item.value5"></ion-radio>
</ion-item>
</ion-col>
</ion-row>
</span>
this is my .ts file
ionViewDidEnter() {
this.itemDetails();
}
itemDetails() {
this.list_launches = [
{ id: 0, item: "item 1", review: 0, value1: 1, value2: 2, value3: 3, value4: 4, value5: 5 },
{ id: 1, item: "item 2", review: 0, value1: 1, value2: 2, value3: 3, value4: 4, value5: 5 },
{ id: 2, item: "item 3", review: 0, value1: 1, value2: 2, value3: 3, value4: 4, value5: 5 },
{ id: 3, item: "item 4", review: 0, value1: 1, value2: 2, value3: 3, value4: 4, value5: 5 },
{ id: 4, item: "item 5", review: 0, value1: 1, value2: 2, value3: 3, value4: 4, value5: 5 },
{ id: 5, item: "item 6", review: 0, value1: 1, value2: 2, value3: 3, value4: 4, value5: 5 },
{ id: 6, item: "item 7", review: 0, value1: 1, value2: 2, value3: 3, value4: 4, value5: 5 },
{ id: 7, item: "item 8", review: 0, value1: 1, value2: 2, value3: 3, value4: 4, value5: 5 },
{ id: 8, item: "item 9", review: 0, value1: 1, value2: 2, value3: 3, value4: 4, value5: 5 },
{ id: 9, item: "item 10", review: 0, value1: 1, value2: 2, value3: 3, value4: 4, value5: 5 },
]
}

Found the solution but needed to compromise with radio-button
here's the thing I done in my codes
my html
<ion-list>
<ion-list-header>
Select Your Preference
</ion-list-header>
<ion-item no-lines *ngFor="let list of prices_details; let i = index;">
<ion-label text-wrap *ngIf="list.size" style="font-size:12px; color:black;">
{{list.size}}
</ion-label>
<ion-label fixed text-right style="font-size:12px; color:black;">
₹ {{list.discounted_price}}
</ion-label>
<ion-checkbox item-left color="secondary" formControlName="list"
(ionChange)="selectSize(list.size ,list.discounted_price, $event.checked)">
</ion-checkbox>
</ion-item>
</ion-list>
in my .ts file
//Adds the checkbox to the array and check if user unchecked it
selectSize(size, discounted_price_pretty, isChecked: boolean) {
if (isChecked === true) {
this.selectedSize.push(size);
this.selectedSizePrice.push(discounted_price_pretty);
}
else {
let index = this.removeCheckedFromSize(size);
this.selectedSize.splice(index, 1);
let priceIndex = this.removeCheckedFromSizePrice(discounted_price_pretty);
this.selectedSizePrice.splice(priceIndex, 1);
}
}

Related

Radio group not working properly when changing the radio group list values frequently in ionic 4

Ionic4 radio group misbehaving while changing the radio group list values dynamically.
Let's take my use case, I have one field country (ion-select) which has a list of countries. Another field called state (ion-radio-group) this will be visible the value based on the country selection. States will be showing fine based on the country selection but the issue is when I click the radio group it will not react in the UI. When I do doubt click the selection will be reflected in the radio group. Why it is not reflected in my first click. Please guide me.
homepage.html
<ion-header>
<ion-toolbar color="primary">
<ion-buttons slot="start">
<ion-menu-button></ion-menu-button>
</ion-buttons>
<ion-title>
Home
</ion-title>
</ion-toolbar>
</ion-header>
<ion-content>
<ion-item>
<ion-label>Country</ion-label>
<ion-select interface="popover" [(ngModel)]="selectedCountry['result']" (ionChange)="changeCountryCallback()">
<ion-select-option *ngFor="let country of pickListValues['country']" value="{{country.choiceValue}}"
[selected]=false>
{{country.choice}}
</ion-select-option>
</ion-select>
</ion-item>
<ion-item *ngIf="selectedCountry['result'] != ''">
<ion-row>
<ion-label>State</ion-label>
</ion-row>
<ion-row>
<ion-list lines="none">
<ion-radio-group (ionChange)="changeStateCallback()" [(ngModel)]="selectedState">
<ion-item *ngFor="let state of selectedCountry['state']">
<ion-label>{{state.choice}}</ion-label>
<ion-radio slot="start" value="{{state.choiceValue}}" [checked]="false"></ion-radio>
</ion-item>
</ion-radio-group>
</ion-list>
</ion-row>
</ion-item>
</ion-content>
homepage.ts
import { Component, OnInit} from '#angular/core';
#Component({
selector: 'app-homepage',
templateUrl: './homepage.html',
styleUrls: ['./homepage.scss'],
})
export class homepage implements OnInit {
private pickListValues = {
country: [{
choiceValue: "in",
choice: "India",
child: {
value: [{
choiceValue: "tn",
choice: "Tamilnadu",
child: {
value: []
}
}, {
choiceValue: "dl",
choice: "Delhi",
child: {
value: []
}
}, {
choiceValue: "mi",
choice: "Mumbai",
child: {
value: []
}
}]
}
}, {
choiceValue: "ci",
choice: "China",
child: {
value: [{
choiceValue: "AH",
choice: "Anhui Province",
child: {
value: []
}
}, {
choiceValue: "GX",
choice: "Guangxi Zhuang",
child: {
value: []
}
}]
}
}, {
choiceValue: "jp",
choice: "Japan",
child: {
value: [{
choiceValue: "gu",
choice: "Gunma",
child: {
value: []
}
}, {
choiceValue: "kw",
choice: "Kanagawa",
child: {
value: []
}
}, {
choiceValue: "oki",
choice: "Okinawa",
child: {
value: []
}
}, {
choiceValue: "tok",
choice: "Tokushima",
child: {
value: []
}
}]
}
}]
}
selectedCountry = {
result: "",
state: []
}
selectedState: any;
constructor() {
}
ngOnInit() {
}
changeCountryCallback() {
console.log("Country Value : ", this.selectedCountry['result']);
this.pickListValues['country'].forEach(element => {
console.log("Element : ", element);
if (element['choiceValue'] == this.selectedCountry['result']) {
this.selectedCountry['state'] = [];
this.selectedCountry['state'] = element['child']['value'];
}
})
}
changeStateCallback() {
console.log("State Value : ", this.selectedState);
}
}
My expected behavior is the radio group to be working fine with a single click after changing the country values frequently
Please watch up to end of the video you can understand my issue. Click here for video
<ion-content>
<ion-item>
<ion-label>Country</ion-label>
<ion-select interface="popover" [(ngModel)]="selectedCountry['result']" (ionChange)="changeCountryCallback()">
<ion-select-option *ngFor="let country of pickListValues['country']" value="{{country.choiceValue}}" [selected]=false>
{{country.choice}}
</ion-select-option>
</ion-select>
</ion-item>
<ion-item *ngIf="selectedCountry['result'] != ''">
<ion-row>
<ion-label>State</ion-label>
</ion-row>
<ion-row>
<ion-list lines="none">
<ion-radio-group (ionChange)="changeStateCallback()" [(ngModel)]="selectedState">
<ion-item *ngFor="let state of selectedCountry['state']">
<ion-label>{{state.choice}}</ion-label>
<ion-radio slot="start" value="{{state.choiceValue}}" [checked]="selectedState==state.choiceValue"></ion-radio>
</ion-item>
</ion-radio-group>
</ion-list>
</ion-row>
</ion-item>
</ion-content>
You can accomplish by the above mentioned way([checked]="selectedState==state.choiceValue"). Here I checked which one is selected from the passed array. So on the first click, it should be working fine. Please try it and share the feedback.
<div>
<ion-label class="heading">Gender</ion-label>
<div *ngFor='let gend of gen'>\\ gen have my details
<ion-radio-group [(ngModel)]="register.Gender" [ngModelOptions]="{standalone: true}">
<ion-row style='margin-top:10px'>
<ion-col size='10'>
<ion-label style='color: #b4b4b4;margin:0 0 0 40px'> {{gend.name}}</ion-label>
</ion-col>
<ion-col size='2'>
<ion-radio [value]="gend.name"></ion-radio>\\value bind to ngModel
</ion-col>
</ion-row>
</ion-radio-group>
</div>
</div>

Set default value for an ion-select-item dynamically

I'm having some mind blow working with ionic 4, I'm trying to set a default value for an ion-select-option dynamically but I'm not getting the correct behavior
I want to load the data into the ion-select and then assign the first value
HTML
<ion-header>
<ion-toolbar>
<ion-title>home</ion-title>
</ion-toolbar>
</ion-header>
<ion-content>
<div style="height: 30%;"></div>
<ion-item>
<ion-label>Ubicación</ion-label>
<ion-select [(ngModel)]="ubicacion" okText="Aceptar" cancelText="Cancelar">
<ion-select-option *ngFor="let ubicacion of ubicaciones">{{ubicacion.nombre}}
</ion-select-option>
</ion-select>
</ion-item>
<ion-item>
<ion-label>Fruta</ion-label>
<ion-select [(ngModel)]="selfruits">
<ion-select-option *ngFor="let fruit of fruits" [value]="fruit">{{fruit.name}}</ion-select-option>
</ion-select>
</ion-item>
<div style="height: 25%;"></div>
</ion-content>
<ion-footer>
<ion-toolbar>
<ion-button expand="block" (click)="goForward('check-in')">Control</ion-button>
<ion-button expand="block" (click)="goForward('item-list')">Check list</ion-button>
</ion-toolbar>
</ion-footer>
TS
import { Component, OnInit } from '#angular/core';
import { NavController } from '#ionic/angular';
import { Maquina } from 'src/app/model/control/maquina';
import { ControlService } from 'src/app/services/control.service';
import { Ubicacion } from 'src/app/model/control/ubicacion';
import { GeneralService } from 'src/app/services/general.service';
#Component({
selector: 'app-home',
templateUrl: './home.page.html',
styleUrls: ['./home.page.scss'],
})
export class HomePage implements OnInit {
ubicaciones: Ubicacion[]
ubicacion
constructor(
private navController: NavController,
private controlService: ControlService,
private generalService: GeneralService,
) { }
fruits = [
{ id: 1, name: 'apple' },
{ id: 2, name: 'banana' },
{ id: 3, name: 'cherry' },
];
selfruits = [this.fruits[1]];
ngOnInit() {
this.fillUbicaciones()
}
fillUbicaciones() {
this.controlService.getUbicaciones().subscribe(x => {
this.ubicaciones = x
console.log("ubicaciones", x)
this.ubicacion = x[1]
})
}
changeUbicacion(value) {
console.log("changeUbicacion", value.detail.value);
// this.ubicacion = this.ubicaciones.find(x => x.nombre == value.detail.value)
}
goForward(action) {
this.generalService.goForward(action)
}
}
This is my data source : https://api.myjson.com/bins/191wsg
You are specifying the second element by using index 1, you should use this.fruits[0] to get the first item in the array.
fruits = [
{ id: 1, name: 'apple' }, // 0
{ id: 2, name: 'banana' }, // 1
{ id: 3, name: 'cherry' }, // 2
];
selfruits = [this.fruits[0]];
You don't need to wrap selFruits in an array, so you can just do:
selFruits = this.fruits[0];

How to add text-area and select to the Alert in Ionic

I am working on Ionic App and I want to show I am showing the input fields in the alert but the problem is that, I am not able to show the textarea and the select box in the alert controller.
This is my popupdetails.ts file:
import { Component } from '#angular/core';
import { IonicPage, NavController, NavParams, LoadingController, AlertController } from 'ionic-angular';
#IonicPage()
#Component({
selector: 'page-checkout',
templateUrl: 'checkout.html',
})
export class CheckoutPage {
constructor(public navCtrl: NavController, public navParams: NavParams,
public loadingCtrl: LoadingController, private alertCtrl: AlertController) {
}
presentPrompt() {
let alert = this.alertCtrl.create({
title: 'Submit Shipping Details',
inputs: [
{
name: 'name',
placeholder: 'Name'
},
{
name: 'mobilenumber',
placeholder: 'Mobile Number',
type: 'number'
},
{
name: 'pincode',
placeholder: 'Pincode',
type: 'number'
},
{
name: 'state',
placeholder: 'State',
},
{
name: 'city',
placeholder: 'City',
},
{
name: 'address',
placeholder: 'Address',
},
],
buttons: [
{
text: 'Cancel',
role: 'cancel',
handler: data => {
console.log('Cancel clicked');
}
},
{
text: 'Submit',
handler: data => {
console.log('Submit clicked');
}
}
]
});
alert.present();
}
}
In this, I have used the alert controller to the input fields but the problem is that, I am not able to show the textarea and the select box in the alert controller.
This is my output currently coming.
I want this type of output with textarea and the select box.
Any help is much appreciated.
https://stackblitz.com/edit/ionic-x1os3c please check this link may hope it will help you
<ion-content padding style="background:white">
<ion-list no-lines>
<form>
<p style="font-weight:bold">Name</p>
<ion-item>
<ion-label hidden></ion-label>
<ion-input style="border:1px solid black" type='text'></ion-input>
</ion-item>
<p style="font-weight:bold">Mobile</p>
<ion-item>
<ion-label hidden></ion-label>
<ion-input style="border:1px solid black" type='tel'></ion-input>
</ion-item>
<p style="font-weight:bold">Country</p>
<ion-item>
<ion-label hidden></ion-label>
<ion-input style="border:1px solid black" readonly="true" type='text'></ion-input>
</ion-item>
</form>
<ion-grid>
<ion-row>
<ion-col>
<button color="secondary" ion-button float-right>Add</button>
<button color="light" ion-button float-right>Close</button>
</ion-col>
</ion-row>
</ion-grid>
</ion-list>
</ion-content>

Angular2 patch input value inside formGroup

I need update inputs value inside each form group after server responce
TS
initAddressRows() {
return this._fb.group({
lat: 0,
lon: 0,
maxTravelTime: this.maxTime[0],
});
}
bindDATA(index) {
this.service.getData().subscribe(
(response) => {this.actualData = response.json()
this.lon = this.actualData.x;
this.lat = this.actualData.y;
// UPDATE THERE 'lat' and 'lon' inputs
},
(error) => console.log('ERROR: ' + error)
);
}
form.value
"addresses": [
{
"lat": 0,
"lon": 0,
"maxTravelTime": "5 min",
},
{
"lat": 0,
"lon": 0,
"maxTravelTime": "5 min",
},
{
"lat": 0,
"lon": 0,
"maxTravelTime": "5 min",
}
]
html
<div class="row" *ngFor="let itemrow of form.controls.addresses.controls; let ind=index" [formGroupName]="ind">
...
<select>
<option (onSelectionChange)="bindDATA(ind)" *ngFor="let option of testLocation; let in=index" [value]="option">
{{ option.text }}
<option>
</select>
...
</div>

Angular 2 remove or add data to form.value object

I need to remove "toys" from form.value object before submit, and add new data to 'price'. But controls must be declared.
form.value object
{
"red": 1,
"green": 3,
"black": "120",
"blue": 3,
"toys": [
{
"bear": 0,
"soldier": 0,
"car": 0
}
],
"price": [
{
"default": 123,
"pre": 3,
"after": 2
},
{
"default": 3,
"pre": 0,
"after": 0
}
]
}
ts
initForm() {
this.form = this._fb.group({
red: 0,
green: 0,
black: '',
blue: 0,
toys: this._fb.array([this.inittoys()]),
price: this._fb.array([this.initprice()]),
});
html
<div class="form-group">
<label for="black">Max travel time</label>
<select class="form-control" id="black" formControlName="black">
<option *ngFor="let t of colors; let i=index" [ngValue]="i">{{t}}</option>
</select>
</div>
You can modify the values in the function before you send the form like this:
<form [formGroup]="yourForm" (ngSubmit)="yourSendFunction(yourForm.value)">
....
in the component:
yourSendFunction(values) {
delete values.toys;
values.price.push({
// Here anything you wants to addd
})
// Next send the values
}