I am facing a problem while using ionic 4, and ionic-select.
The problem comes when i have some data and i am binding the data.
In this example, i already have a pre selected data, when i do so the ion-select does not render properly.
<ion-item class="transparent">
<ion-label position='floating'>{{ 'GENDER_TXT' | translate}}</ion-label>
<ion-select interface="popover" color='medium' [(ngModel)]='Gender' formControlName='genderTxt'>
<ion-select-option *ngFor='let g of Genders' [value]='g'>{{g.GENDER}}</ion-select-option>
</ion-select>
</ion-item>
this.getGendersSub = this.proxy.Get_Genders(param).subscribe((data) => {
this.Genders = data;
this.Gender = this.Genders[0];
});
Demo Image
remove the ngmodel directive[(ngModel)]='Gender' when you use reactive form , you can set the selected value by update form control genderTxt value
this.getGendersSub = this.proxy.Get_Genders(param).subscribe((data) => {
this.Genders = data;
this.form.get(`genderTxt`).setValue(this.Genders[0]);
});
demo 🚀🚀
Related
What I want to do is to show the first row in HTML (in below code) only on a condition using *ngIf. I've done the basic validation, but I have a hard time and can't find how I can do *ngIf accessing an object key directly (and not using an *ngFor before, on a different element). What I want to do is to show the row only when object.key === 'specific value'. I've tried options with "keys", "Object" but nothing seems to work. If you guys have any suggestion I would appreciate it.
my HTML
<ion-grid *ngIf="!isLoading && loadedBio.length > 0">
<ng-container *ngFor="let bio of loadedBio">
<ng-container *ngIf="bio.category === '1'">
<ion-row class="ion-padding">
<ion-col>
<ion-list class="no-last-border">
<ion-item
detail="false"
*ngIf="bio.category === '1'">
<ion-label
[ngStyle]="{
color:
bio.category === '1'
? '#A34F83'
: 'var(--ion-color-secondary)'
}"
class="bioLabel"
>{{bio.friendlyName}}</ion-label>
</ion-item>
</ion-list>
</ion-col>
</ion-row>
</ng-container>
</ng-container>
my JS object I want to access the key from has the following format
loadedBio = [{key: value, key2: value}]
If you need to display each of the properties on your found object, then, in your component, you'd want to convert that found object to an array first - where each element in the array represents a property on the object, and then iterate over it to display each element:
const obj1 = {
a: 'a title',
b: 42,
c: false
};
const arr1 = Object.values(obj1);
Put together that would look like this. First, in the component:
import { Component } from '#angular/core';
#Component({
selector: 'page-home',
templateUrl: 'home.html'
})
export class HomePage {
loadedBio = [{'key': 1, 'key2': 2}, {'key': 3, 'key2': 4}];
obj1 = {
a: 'a title',
b: 42,
c: false
};
arr1 = Object.values(this.obj1);
constructor() {
}
}
And in the view:
<ion-header>
<ion-navbar>
<ion-title>Home</ion-title>
</ion-navbar>
</ion-header>
<ion-content padding>
<ng-container *ngIf="loadedBio">
<ion-list *ngFor="let bio of loadedBio">
<ng-container *ngIf="bio.key === 1">
<ion-item>{{bio.key}}</ion-item>
</ng-container>
</ion-list>
</ng-container>
<ng-container *ngFor="let e of arr1">
<ion-item>{{e}}</ion-item>
</ng-container>
</ion-content>
This should give you an idea of how to handle your situation. Sounds like you want to transform the data in your component, and then iterate over it need be in your view.
Here is a link to the working StackBlitz:
Best to filter your array in the controller, like this
this.filteredBio = this.loadedBio.filter(el=>el.category === 'overall')
and then simply use *ngFor on this filteredBio array. This will only have the objects whose category is 'overall'
Another solution is to implement a custom pipe Refer this
What I want to achieve in the end is to see which form controls individually from my form have changed and to create a new object with them assigning a boolean of true if they were changed or false if not. Please see below what I achieved so far, but I don't think this the right approach as when I'll have more from controls my method will become gigantic. If you guys have any idea how I can approach this I would really appreciate it.
my Html
<form [formGroup]="editProfileForm">
<ion-row>
<ion-col>
<ion-input
*ngIf="profileData"
formControlName="firstName"
placeholder="First Name"
></ion-input>
</ion-col>
</ion-row>
<ion-row>
<ion-col>
<ion-input
*ngIf="profileData"
formControlName="lastName"
placeholder="Last Name"
></ion-input>
</ion-col>
</ion-row>
</form>
<ion-fab
vertical="bottom"
horizontal="center"
slot="fixed"
(click)="onSubmitEditedProfile()">
<ion-fab-button>
<ion-icon name="checkmark-outline"></ion-icon>
</ion-fab-button>
</ion-fab>
my TS
onSubmitEditedProfile() {
if (this.profileData !== null) {
let updatedFirstName = this.editProfileForm.get("firstName").value;
if (this.profileData.firstname !== updatedFirstName) {
}
console.log("it's the same");
} else {
console.log("it's different")
}
And as my approach means, I'll do the same for lastName and so on
Here is the example where you can iterate each form control and identify either its changed or not based on that populate new array of object.
onSubmitEditedProfile() {
const formValue = [];
// iterate over form controls no matter how many control you have.
Object.keys(this.form.controls).map((key) => {
// create a new parsed object
const parsedValue = {
[key]: this.form.get(key).value, // key is the actual form control name
changed: this.form.get(key).dirty // added changed key to identify value change
}
// push each parsed control to formValue array.
formValue.push(parsedValue)
})
console.log(formValue)
}
Here is the stackblitz working DEMO
Hope this address your requirements.
All you need is just to read dirty value on FormGroup or individual FormControl
https://angular.io/api/forms/AbstractControl#dirty
onSubmitEditedProfile() {
if (!this.editProfileForm.dirty) {
console.log("it's the same");
} else {
console.log("it's different")
}
I have a clarification, Basically i am passing a list from parent page to Ionic modal. In modal, i will iterating over a list. i am basically modifying a property of an object on click of ion-item.
Below is the html code in the modal.
<ion-card *ngFor="let item of items">
<ion-row>
<ion-col size="3">
<ion-img width="80" height="80" [src]="item.imagePath"></ion-img>
</ion-col>
<ion-col size="7" >
<ion-label class="item-name">item.name</ion-label>
<ion-label class="item-price">item.cost</ion-label>
<ion-label class="item-date">item.date</ion-label>
</ion-col>
<ion-col size="2">
<ion-icon class="select-icon" name="add-circle" (click)="updateObj(item)"></ion-icon>
</ion-col>
</ion-row>
</ion-card>
In modal.component.ts
ngOnInit() {
this.items = this.navParams.get("items");
}
dismissModal(){
this.modalCtrl.dismiss();
}
updateObj(object){
if(object){
object.status = true
}
}
i am using navParams to get the list from parent page to the modal. When i click on ion-item i will be calling updateObj method where i am updating the status of object to true. Everything works fine.
But when i update the object in the modal, the original list sent to the modal also gets updated.
Could anyone explain why updating the list in the modal updates the original list. Is it bcoz of using navParams as it referers to the list?
In Parent.component.ts
async openSearchModal(){
const modal = await this.modalCtrl.create({
component: CouponSearchPage,
componentProps: { items: this.itemListData,
}
});
This is how i am passing the list to the modal from parent screen.
When you pass this.itemListData to modal, you are passing the reference of the object.
If you don't want to modify the actual object, you can pass a new object.
Try this:
const modal = await this.modalCtrl.create({
component: CouponSearchPage,
componentProps: { items: { ...this.itemListData},
}
});
I need to set default value to ion-select item.
The ion-select above contain list of places, After choosing a place I save it into a localStorage.
What I need this localStorage be the default value of the ion-select,like this:
When the page is changed the ion-select return the placeHolder and no item is selected
CODE:
<ion-item>
<ion-select multiple="false" placeholder="Which Place?" [(ngModel)]="placeId" (ionChange)="showPlace()">
<ion-option class="text-input place-field" *ngFor="let place of places | async;let i = index" value="{{place.id}}">
{{place.name}}
</ion-option>
</ion-select>
</ion-item>
I found a solution to that..
add a AbstractControl to your [(ngModel)].
example:
in yout TS file..
placeForm: FormGroup;
placeId: AbstractControl;
constructor(){
this.placeForm.formBuilder.group({
placeId: ['', Validators.required],
});
this.placeForm.get('placeId').setValue(place.id);
}
in your html
just add this [(ngModel)]="placeForm.placeId"
If you have the index value you can just fetch that from localstorage and when the page loads you can save it in a variable and then use it to bind to the selected property on ion-option:
html:
<ion-item>
<ion-select multiple="false" placeholder="Which Place?" [(ngModel)]="placeId" (ionChange)="showPlace()">
<ion-option class="text-input place-field" *ngFor="let place of places | async;let i = index" [selected]="i == selectedIndex" value="{{place.id}}"> // the variable selected index will be a number and will select the item matching with the index from the array.
{{place.name}}
</ion-option>
</ion-select>
</ion-item>
in ts:
selectedIndex: number;
constructor(){
this.selectedIndex = localStorage.getItem('index') //
}
I solved
the ion-select have the two way data binding with placeId
<ion-select multiple="false" placeholder="Which Place?" [(ngModel)]="placeId" (ionChange)="showPlace()">
<ion-option class="text-input place-field" *ngFor="let place of places | async;" value="{{place.id}}">
{{place.name}}
</ion-option>
</ion-select>
After Selecting a place I saved the id of the selected place inside the local storage. Then on the ionViewDidLoad() I init the the variable this.placeId
this.placeId = localstorage.getItem('foo')
and it work properly.
My mistake: I was saving the name of the place in the localstorage and not the id of the place
Thanks
In ionic 4
ionViewDidEnter() {
let parametros = this.navParams.get('parametros');
this.cuentaBancaria.empresa._id = parametros.empresa;
this.cuentaBancaria.moneda._id = parametros.moneda;
}
How to access selected choice in dynamically created ionic list ionic2 ?
This is part of my .ts file where routeArr is my array , in which i am retrieving data from firebase-
this.routeList.subscribe(snapshots => {
snapshots.forEach(snapshot => {
var valueToPush = new Array();
valueToPush[0] = snapshot.key;
valueToPush[1] = snapshot.val();
this.routeArr.push(valueToPush);
console.log(this.routeArr[i]);
console.log("Array Length = ",this.routeArr.length); // See the length of the array growing
i=i+1;
});
});
This is part of my HTML file where i am displaying radio buttons dynamically
<ion-item>
<ion-label floating>Trip</ion-label>
<ion-select [(ngModel)]="routeArr">
<ion-option *ngFor="let route of routeArr" value="{{route[0]}}">{{route[0]}}
</ion-option>
</ion-select>
</ion-item>