ionic2 dynamic ion-select ..., get selected value in html - html

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>

Related

How to use *ngIf on an object to check if key has a specific value without doing *ngFor firstly?

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

How to check if each form control changed their value in reactive forms?

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")
}

ionic select won't render properly with dynamic values? Ionic 4

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 🚀🚀

Ionic JSON, add card to favorites

I have a JSON Parse in my project and its work fine
let data:Observable<any>;
data = this.http.get(API);
data.subscribe(result => {
this.items = result;
this.saveData();
});
HTML:
<ion-card *ngFor="let item of items">
<ion-card-content id="{{item.id}}">
....
....
</ion-card-content>
</ion-card>
Now I want a 'Favorite' function.
I have an icon with a click event.
How I do, that when anyone clicks on the icon he add the specific card to his favorites and he can show his favorites on another page?

How to set default value ion-select item?

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;
}