ionic how to get value of select - ionic4

html:
<ion-list>
<ion-item>
<ion-label><b>Select</b></ion-label>
<ion-select [compareWith]="compareWith">
<ion-select-option *ngFor="let item of items">{{item.title}}</ion-select-option>
</ion-select>
</ion-item>
</ion-list>
typescript:
items:any;
compareWithFn = (o1, o2) => {
return o1 && o2 ? o1.id === o2.id : o1 === o2;
};
compareWith=this.compareWithFn;
constructor(public http:HttpClient) {
this.loadData()
}
loadData(){
let data:Observable<any>
const headers = new HttpHeaders;
data=this.http.get('https://jsonplaceholder.typicode.com/posts')
data.subscribe(result=>{
this.items=result
console.log(result)
console.log(result.valid)
})
}
they are same code of my application
i have list select of title ,i whould get the value it was selected
How can i get the value selected of the list ?

Use data binding to save the value of select element
<ion-select [compareWith]="compareWith" [(ngModel)]="mySelectValue">
<ion-select-option *ngFor="let item of items">{{item.title}}</ion-select-option>
</ion-select>
typescript:
mySelectValue:any; //Declare a variable mySelectValue
let value=this.mySelectValue;//Use the value of select
Also,
If you want to call a function when select value is changed, use (ionChange)="myfunction()"
<ion-select [compareWith]="compareWith" [(ngModel)]="mySelectValue" (ionChange)="myfunction()" >

Related

how to select a default value in q-select from quasar?

I need my q-select to select the "name" depending on the previously assigned "id".
Currently the input shows me the "id" in number and not the name to which it belongs.
<q-select
class="text-uppercase"
v-model="model"
outlined
dense
use-input
input-debounce="0"
label="Marcas"
:options="options"
option-label="name"
option-value="id"
emit-value
map-options
#filter="filterFn"
#update:model-value="test()"
>
<template v-slot:no-option>
<q-item>
<q-item-section class="text-grey"> No results </q-item-section>
</q-item>
</template>
</q-select>
Example I would like the name that has the id: 12 to be shown loaded in the q-select.
const model = ref(12);
const options = ref([]);
const filterFn = (val, update) => {
if (val === "") {
update(() => {
options.value = tableData.value;
});
return;
}
update(() => {
const needle = val.toLowerCase();
options.value = tableData.value.filter((v) =>
v.name.toLowerCase().includes(needle)
);
});
};
I'm running into the same issue and couldn't find a proper way to set default value of object type.
I ended up use find() to look for the default value in the options and assign it on page created event.
created() {
this.model = this.options.find(
(o) => o.value == this.model
);
}

Pre-select a VUE2 drop-down

I have a vue2 app which I need to pre-select a dropdown but for the life of me, I can't figure it out.
I have looked and tried everything in:
How to preselect current value in a select created with v-repeat in Vue.js
Normal HTML
<select ref="courierList" id="courierList" class="form-control" v-model="shippingDetails.selectedCourier" #change="selectedCourierDd">
<option :value="courier.name" v-for="(courier, i) in couriers" :key="i">
{{ courier.name }}
</option>
</select>
data() {
return {
couriers: [],
.... OTHER DATA ITEMS
}
},
beforeMount() {
this.fetchCouriers();
},
fetchCouriers() {
axios.get('/couriers')
.then((response) => {
this.couriers = response.data.couriers;
.... OTHER CODE
Tried code > 1
Adding the below to the option
selected="{{ courier.name === preselectedCourierName ? 'true' : 'false' }}">
also tied without the true/false
Tried code > 2
Adding the below to the option
v-bind:selected="courier === preselectedCourierName"
and the below
data() {
return {
.... OTHER DATA ITEMS
preselectedCourier: [],
preselectedCourierName: ''
}
fetchCouriers() {
axios.get('/couriers')
.then((response) => {
this.couriers = response.data.couriers;
.... OTHER CODE
console.log('couriers', this.couriers[0])
this.preselectedCourier = this.couriers[0];
this.preselectedCourierName = this.preselectedCourier.name;
console.log('preselectedCourier', this.preselectedCourier)
console.log('preselectedCourierName', this.preselectedCourierName)
gives
Tried code > 3
<option :value="courier.name" v-for="(courier, i) in couriers" :key="i" :selected="courier.name === 'APC'">
no errors but dropdown still not pre-selected
The fix is in the mounted hook set the v-model of the select
<select v-model="shippingDetails.selectedCourier">
mounted() {
this.shippingDetails.selectedCourier = 'APC';
}
Give me exactly what i wanted

Infinite loop warning in vue table rendering

I tried calling a function while rendering a table, and based on condition in the function i assigned that value and displayed it using string interpolation, but i am getting infinite loop error.
Below is url for code
jsfiddle.net/amit_bhadale/5kct0au1/2/
Below is function
checkData(day, time){
let that = this
let result = this.serverData.some(a=>{
if(a.Day === day && a.Time === time){
that.cellId = a.id
// This is giving infinite loop error
// if i chnage it to this then it works
// that.cellId = 'Some normal string'
}
return (a.Day === day && a.Time === time)
})
return result
}
HTML part
<table>
<tr v-for="(time, i) in time" :key="i">
<td v-for="(day, j) in day" :key="j">
<span v-if="checkData(day, time)">
</span>
<span v-else>
No data in this cell
</span>
</td>
</tr>
</table>
Dont update props multiple times with different values within in render cycle.
To seperate those you can just put it into a single component:
e.g.:
{
props: ['time', 'day', 'serverData'],
computed: {
cellValue(){
let val = "No data in this cell"
this.serverData.some(a=>{
if(a.Day === this.day && a.Time === this.time){
val = a.id;return true;
}
})
return val
}
}
}
<template>
<span>cellValue</span>
</template>

how to create dynamic input filters for columns in bootstrap-vue 2.0

I'm trying to create some dynamic filters in bootstrap-vue 2.0.0-rc.11 for the bootstrap-table columns
In my example I did this
<b-table class="io-store-list-table table-striped" show-empty hover stacked="md" :items="stores" :fields="storeFields" :current-page="currentPage" :per-page="perPage" :filter="filter" :sort-by.sync="sortBy" :sort-desc.sync="sortDesc" :sort-direction="sortDirection" #filtered="onFiltered" empty-filtered-text="{l s='There are no records matching your request' mod='ioweb_slocator'}">
<template slot="top-row" slot-scope="data">
<th v-for="field in fields">
<input v-if="field.filterable" type="text" #click.stop value="" />
</th>
</template>
<template v-for='field in formatted' :slot='field' slot-scope='row'>
<span v-html='row.value'></span>
</template>
</b-table>
<b-row>
<b-container>
<b-col xs="12" class="my-1 io-pagination">
<b-pagination :total-rows="totalRows" :per-page="perPage" v-model="currentPage" class="my-0"/>
</b-col>
</b-container>
</b-row>
</b-table>
Which renders a table like this
Now I'm attempting to filter the items based on what value is entered in each column. For example if I type mypartnername at the input box below Partner column, I would like to dynamically filter the items based on the row key called partner but I'm not sure how to approach this.
Based on the accepted answer I was able to create a structure that helped me like this.
Step 1:
Create a property filteredResults and set it equal to my unfiltered items property
let app = new Vue({
el: "#app",
data() {
return {
...
stores: stores,
groups: groups,
totalRows: stores.length,
filters: [],
loop: 0,
filteredResults: stores,
}
},
Step 2
Used filteredResults in the :items slot
Step 3
Create a single function to set the filters
methods: {
...
setFilter(property, value) {
console.log("Filtering");
this.filters[property] = {};
this.filters[property].value = value;
this.filteredResults = this.stores.filter(item => {
let keep = true;
// This is a basic equality filter. What I did in the actual code was to have an object with filter functions for each key. If a key was missing, it defaulted to straight equality.
this.fieldKeys.forEach(key => {
keep =
keep &&
(this.filters[key] === undefined || this.filters[key].value === undefined || this.filters[key].value === "" || item[key].match(this.filters[key].value));
});
return keep;
});
},
},
what about something like this? I dont know if i got your problem right.
<input v-if="field.filterable" #onchange="setFilter(field.property, $event.target.value)" type="text" #click.stop />
in the setFilter function you could do something like this:
setFilter(property, value) {
this.filters[property].value = value
}
get your results with a computed property
filteredResults(){
return users = this.users.filter((item) => {
for (var key in this.filters) {
if (item[key].value === undefined || item[key].value != filter[key])
return false;
}
return true;
}
}
I dont know if it works, couldnt test it. I am curious about the solution here.

Updating v-model data in form inputs with a series of methods in a Vuetify project?

I am attempting to update a series of v-text-fields (type='number') so that after the user has entered in a numeric value, the number shown in the input will be updated with commas (so a value of 5032 would become 5,032 for example). I found this article and was able to accomplish what I'm after with a single input using the example provided...
Markup:
<div id="app">
<div v-if="visible === true">
Enter Amount: <br>
<input type="number"
v-model="amount"
placeholder="Enter Amount"
#blur="onBlurNumber"/>
</div>
<div v-if="visible === false">
Enter Amount: <br>
<input type="text"
v-model="amount"
placeholder="Enter Amount"
#focus="onFocusText"/>
</div>
Script:
data: {
amount: null,
temp: null,
visible: true
},
methods: {
onBlurNumber() {
this.visible = false;
this.temp = this.amount;
this.amount = this.thousandSeprator(this.amount);
},
onFocusText() {
this.visible = true;
this.amount = this.temp;
},
thousandSeprator(amount) {
if (amount !== '' || amount !== undefined || amount !== 0 || amount !== '0' || amount !== null) {
return amount.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",");
} else {
return amount;
}
}
}
...but I want to make the methods generic enough to work with any numeric v-text-fields I am using. I have been able to update a parameter value within my methods, but have been unable to actually update the v-model data of the v-text-field.
Markup:
<div id="app">
<div v-if="visible === true">
<v-text-field
class="mb-3 d-inline-block"
type="number"
prepend-inner-icon="attach_money"
v-model="amount"
label="Amount"
mask="##########"
outline
:rules="[v => !!v || 'Amount is required']"
#blur="onBlurNumber(amount)"
required>
</v-text-field>
</div>
<div v-if="visible === false">
<v-text-field
class="mb-3 d-inline-block"
prepend-inner-icon="attach_money"
v-model="amount"
label="Amount"
outline
#focus="onFocusText(amount)"
>
</v-text-field>
</div>
Script:
onBlurNumber(data) {
this.visible = false;
this.temp = data;
data = this.thousandSeprator(data);
},
onFocusText(data) {
this.visible = true;
data = this.temp;
},
I can log the value of data in these methods and confirm that the commas are being applied correctly, but now I don't know how to send the data value back to update the v-text-field's v-model. I experimented with selecting the v-text-field using a ref value but the ref turns up as an undefined value when the method is triggered.
Does anyone know how I can update the v-model of the v-text-field using arguments in this sort of fashion so the methods are reusable?
I assume that you have multiple data items for each of the text fields:
data: function() {
return {
// Field 1
temp1: null,
amount1: null,
visible1: true,
// Field 2
temp2: null,
amount2: null,
visible2: true
}
}
In your markup, when calling the method you could then pass the name of the property, or maybe its suffix.
<v-text-field #blur="onBlurNumber('2')"
And in your script, you could update the data items by using dynamic properties:
methods: {
onBlurNumber(suffix) {
this["visible" + suffix] = false;
this["temp" + suffix] = this["amount" + suffix];
this["amount" + suffix] = this.thousandSeprator(this["amount" + suffix]);
},
Here's a working example of two independent text inputs that are calling the same methods to achieve this. We could refactor this to reduce the number of data items using arrays if needed.