Dynamic dropdown not working properly in ionic 3 - ionic-framework

You can change here also ->https://stackblitz.com/edit/ionic-djze7u
home.html
<ion-content padding>
<ion-card>
<ion-card-content *ngFor="let item of users">
<ion-row>
<ion-label>{{item.name}}:</ion-label>
<ion-label>{{item.age}}</ion-label>
Here is the loop which I want to show value into dropdown according to item.term
<ion-select [(ngModel)]="check[item.age]">
<ion-option value="0" selected>0</ion-option>
<ion-option *ngFor="let v of caldrop(item.term)" value="{{v}}">
{{v}}
</ion-option>
</ion-select>
</ion-row>
</ion-card-content>
</ion-card>
</ion-content>
Home.ts
export class HomePage {
according to this term vale dropdown will show from 0 to this term value
users:any = [
{ name: 'Composite Factory', age: 1, term:2 },
{ name: 'Todd', age: 2, term:1 },
{ name: 'Lisa', age: 3, term:4 }
];
check:any = [];
constructor(public navCtrl: NavController) {
}
caldrop(myval:any){
console.log(myval)
let myarr:any = [];
for(let i=1;i<=myval;i++){
myarr.push(i);
}
return myarr;
}
}

Related

Ion-item with *ngFor in a dropdown

I would like to set a button that opens and hides some ion-item in a dropdown.
I know that there might be a solution in the docs but I am unable to find it
<ion-header>
<ion-toolbar>
<ion-title>Technical Information</ion-title>
</ion-toolbar>
</ion-header>
<ion-content>
<ion-list>
<ion-list-header>
<ion-label>Manuales</ion-label>
</ion-list-header>
<ion-item *ngFor="let m of manuals">
<ion-label>{{m}}</ion-label>
</ion-item>
</ion-list>
<!-- Other <ion-list-header>s and <ion-item>s -->
</ion-content>
I would like to hide and show all Items when clicking on each ion-list-header, show his own ion-item with *ngFor, like if there are 20 manuals, dropdown all 20 manuals and hide others ion-list-headers...
Is there a way to do it with this structure or maybe with another?
Try this:
<ion-header>
<ion-toolbar>
<ion-title>Technical Information</ion-title>
</ion-toolbar>
</ion-header>
<ion-content>
<ion-list *ngFor="let m of manuals; let i=index">
<ion-list-header>
<ion-label (click)="showOrHide(i)">Manuales</ion-label>
</ion-list-header>
<ion-list id="{{i}}" style="display:none">
<ion-item *ngFor="let m of m.list">
<ion-label>{{m}}</ion-label>
</ion-item>
</ion-list>
</ion-list>
</ion-content>
In .ts component:
import { Component } from '#angular/core';
import { NavController , AlertController } from 'ionic-angular';
#Component({
selector: 'page-home',
templateUrl: 'home.html'
})
export class HomePage {
manuals = [{
id:1,
list: ["1","2","3"]
},
{
id:2,
list: ["1","2","3"]
},
{
id:3,
list: ["1","2","3"]
},
{
id:4,
list: ["1","2","3"]
}]
constructor() {
}
showOrHide(id){
const listItemShow = document.getElementById(id);
if(listItemShow.style.display === "none")
listItemShow.style.display = "block"
else
listItemShow.style.display = "none"
}
}

Ionic 4: How to pre select values in an ion-select component

I am developing an Ionic 4 app.
I need to pass data from a list of users to a form in order to modify some attributes of this particular user.
I passed the data from the list (the user) to an other page containing the form. I saved this data in local variables in the .ts of the form.
Now, I have some trouble to make an ion-select component pre-select this data. I have no troubles for an ion-input though.
I tried to do so with a double data binding with [(NgModel)] and a value attribute but it didn't work.
Any help here will be appreciated.
Edit: Here is my code.
The .ts file:
serviceList: Service[];
isModifying = false;
username: string;
password: string;
firstName: string;
lastName: string;
service: number;
codivRH: any;
profil: string;
constructor(private sqlP: SqlProvider, private route: ActivatedRoute, private router: Router) {
this.route.queryParams.subscribe(params => {
if (this.router.getCurrentNavigation().extras.state) {
this.firstName = this.router.getCurrentNavigation().extras.state.userFirstname;
this.lastName = this.router.getCurrentNavigation().extras.state.userLastname;
this.service = this.router.getCurrentNavigation().extras.state.userService;
this.codivRH = this.router.getCurrentNavigation().extras.state.userCodiv;
this.profil = this.router.getCurrentNavigation().extras.state.userProfil;
this.isModifying = true;
}
});
}
Here is the .html file:
<ion-item>
<ion-label> Service </ion-label>
<ion-select [(ngModel)]="service" name="service">
<ion-select-option *ngFor="let mservice of serviceList" value="mservice.Id" ngDefaultControl> {{ mservice.Nom }} </ion-select-option>
</ion-select>
</ion-item>
<ion-item>
<ion-label> CodivRH </ion-label>
<ion-select [(ngModel)]="codivRH" name="codiv">
<ion-select-option value="1"> Oui </ion-select-option>
<ion-select-option value="0"> Non </ion-select-option>
</ion-select>
</ion-item>
<ion-item>
<ion-label> Profil </ion-label>
<ion-select [(ngModel)]="profil" name="profil">
<ion-select-option value="user"> Utilisateur</ion-select-option>
<ion-select-option value="admin"> Admin </ion-select-option>
<ion-select-option value="Superadmin"> SuperAdmin </ion-select-option>
</ion-select>
</ion-item>
Here is working example
in your ts
selected;
defaultList = [
{
id: 0,
key: "BILLPAYMENT",
value: "Wallet_1002"
},
{
id: 1,
key: "REQUESTMONEY",
value: "Wallet_1002"
},
{
id: 2,
key: "SENDMONEY",
value: "Wallet_1002"
},
{
id: 3,
key: "QUICKPAYMENT",
value: "Wallet_1002"
}
];
constructor() {
this.selected={
id: 0,
key: "BILLPAYMENT",
value: "Wallet_1002"
};
}
.html
<ion-item>
<ion-select [(ngModel)]="selected" [compareWith]="compareFn">
<ion-option *ngFor="let default of defaultList" [value]="default">{{default.key}}</ion-option>
</ion-select>
</ion-item>
I have the same problem using ReactiveForms. Here my form: update.html
<form *ngIf="datosBasicosForm" name="datosBasicosForm" [formGroup]="datosBasicosForm">
<ion-list>
<ion-item>
<ion-label position="floating">Tipo de Actividad </ion-label>
<ion-select id="field_tipoDeActividad" placeholder="Seleccionar" formControlName="tipoDeActividad"
[compareWith]="compareTipoDeActividad" >
<ion-select-option [value]="tipoDeActividadOption"
*ngFor="let tipoDeActividadOption of tipoDeActividads; trackBy: trackTipoDeActividadById">
{{tipoDeActividadOption.nombre}}</ion-select-option>
</ion-select>
</ion-item></ion-list></form>
Then in the update.ts I load some data to fill de tipoDeActividads array of TipoDeActividad and the variable actividad of Actividad from the DB with id passed as a parameter:
export class ActividadUpdatePage implements OnInit {
datosBasicosForm = this.formBuilder.group({
id: [],
tipoDeActividad: [null, [Validators.required]],
});
async ngOnInit() {
this.tipoDeActividadService.query()
.subscribe(data => { this.tipoDeActividads = data.body; }, (error) =>
this.onError(error));
this.activatedRoute.data.subscribe((response) => {
this.updateForm(response.data);
});
}
updateForm(actividad: Actividad) {
this.datosBasicosForm.patchValue({
id: actividad.id,
tipoDeActividad: actividad.tipoDeActividad,
});
}
As you can see I load everything in the ngOnInit and do a patch of the values received in the form.
But even when I click the ion-select and the option is selected, the problem is that it doesn't show the preselected value when the form load...
the compareWith function is as follows:
compareTipoDeActividad(first: TipoDeActividad, second: TipoDeActividad): boolean {
return first && second ? first.id === second.id : first === second;
}
So I'm thinking it may be something related to the type of object I'm dealing with? or with the asynchronous load calls that are not ready when the form is rendered?
Any help will be much appreciated, thanks.

ionic 3 calculate items after doing drag and drop

I'm very new in software project and currently working on final year project, mobile apps using ionic 3 framework. I have drag and drop function, first bucket with list of items and second bucket is empty. When I want to drag the items from 1st bucket to the 2nd bucket, I want to calculate the price for each entry at the second bucket but I really don't have idea to do it. Can someone help me with the codes :(
this is my calculate.ts
q1 = [];
q2 = [];
details: any = [];
totalPrice: number;
constructor(public navCtrl: NavController, private postPvdr: PostProvider, public navParams: NavParams, public dragulaService: DragulaService, public AlertController:AlertController) {
dragulaService.drop().subscribe((value) => {
console.log(value)
});
const bag: any = this.dragulaService.find('bag');
if (bag !== undefined ) this.dragulaService.destroy('bag');
this.dragulaService.createGroup('bag', {
revertOnSpill: true,
});
}
ionViewDidLoad() {
this.details = [];
this.getlist();
this.getTotalPrice()
}
getlist(){
let body = {
aksi: 'get_user'
};
this.postPvdr.postData(body, 'aksi_user.php').subscribe(data => {
for(let detail of data.result){
this.details.push(detail);
console.log(data);
}
});
}
getTotalPrice(){
let totalPrice = 0;
let body = {
aksi: 'get_user'
};
this.postPvdr.postData(body, 'aksi_user.php').subscribe(data => {
for(let detail of data.result){
totalPrice += Number.parseFloat(detail.dest_budget);
}
});
console.log(totalPrice);
return totalPrice;
}
these lines of codes seem weird because i just do try n error
this is my calculate.html
<ion-content padding>
<ion-row>
<ion-col width-50 class="left">
<div class="header">First Bucket</div>
<ion-list [dragula]='"bag"' [(dragulaModel)]="details">
<button ion-item *ngFor="let detail of details">
{{detail.dest_name}}
<p>{{ detail.dest_budget}}</p>
</button>
</ion-list>
</ion-col>
<ion-col width-50 class="right">
<div class="header">Second Bucket</div>
<ion-list [dragula]='"bag"' [(dragulaModel)]="q2">
<div ion-item *ngFor="let detail of q2">
{{detail.dest_name}}
<p>{{ detail.dest_budget }}</p>
</div>
</ion-list>
</ion-col>
</ion-row>
</ion-content>
<ion-footer>
<ion-toolbar>
<ion-title>Total Price:</ion-title>
</ion-toolbar>
</ion-footer>
the total price should be showing at the footer
here is my interface looks like
hope someone can help :)
call function here
dragulaService.drop().subscribe((value) => {
this.getTotalPrice();
});
modify the function
getTotalPrice(){
this.totalPrice = 0;
let body = {
aksi: 'get_user'
};
this.postPvdr.postData(body, 'aksi_user.php').subscribe(data => {
for(let detail of data.result){
this.totalPrice += Number.parseFloat(detail.dest_budget);
}
});
}
and bind model
<ion-footer>
<ion-toolbar>
<ion-title>Total Price:{{totalPrice}}</ion-title>
</ion-toolbar>
</ion-footer>

Ionic 3 : How to make checkboxes behavior like radio-button

I have a list of checkboxes and I want to make them behave like radio button
How can I do this?
I tried using radio button but I am not getting the value of the user input so I dropped the idea of radio button and implement checkbox where i get the proper value & everything is perfect except the multiple checkbox selection I want to remove that
Here is my code:
selectOption(name, isChecked) {
if (isChecked === true) {
this.selectednames.push(name);
} else {
let index = this.removeCheckedFromName(name);
this.selectednames.splice(index, 1);
}
}
removeCheckedFromName(names: String) {
return this.selectednames.findIndex((ref) => {
return ref === names;
});
}
in my HTML
<ion-list>
<ion-list-header>
Choose Your Team
</ion-list-header>
<ion-item *ngFor="let names of name; let i = index">
<ion-label>{{name}}</ion-label>
<ion-checkbox item-left color="secondary" formControlName="name"
(ionChange)="selectOption(name, $event.checked)">
</ion-checkbox>
</ion-item>
</ion-list>
Any advices is highly appreciated
checkbox-stovr.page.html
<ion-header>
<ion-toolbar>
<ion-title>checkbox-stovr</ion-title>
</ion-toolbar>
</ion-header>
<ion-content>
<ion-list>
<ion-list-header>
Choose Your Team
</ion-list-header>
<ion-item *ngFor="let name of names; let i = index">
<ion-label>{{ name['name'] }}</ion-label>
<ion-checkbox [(ngModel)]="name['isChecked']" (click)="toggle(name)">
</ion-checkbox>
</ion-item>
</ion-list>
</ion-content>
CheckboxStovrPage
import { Component, OnInit } from '#angular/core';
#Component({
selector: 'app-checkbox-stovr',
templateUrl: './checkbox-stovr.page.html',
styleUrls: ['./checkbox-stovr.page.scss'],
})
export class CheckboxStovrPage implements OnInit {
names = [{ name: 'a' }, { name: 'b' }, { name: 'c' }, { name: 'd' },];
public selected: string;
constructor() { }
ngOnInit() {
}
public toggle(selected) {
for (let index = 0; index < this.names.length; index++) {
if (this.names['name'] != selected['name'])
this.names[index]['isChecked'] = null;
}
}
}
Do you want only one value selected at a time ??

ionic 3 youtube api data

I'm having a problem calling the data into the view. Console log is working as I included a screenshot.
ytapiUrl =https://www.googleapis.com/youtube/v3/playlistItems? part=snippet&playlistId='blahblahbla'
getECvideolists(){
return new Promise(resolve => {
this.httpClient.get(this.ytapiUrl).subscribe(ytdata => {
resolve(ytdata);
this.Ecvideos = ytdata;
console.log(ytdata);
}, err => {
console.log(err);
});
});
}
<ion-list *ngSwitchCase="'videos'">
<ion-item *ngFor="let Ecvideo of Ecvideos">
<h2> ***this doesn't display*** {{Ecvideo.items.snippet.title}}</h2>
</ion-item>
</ion-list>
[
items key has an array so you need to iterate it through *ngFor
for example,
<ion-list *ngSwitchCase="'videos'">
<ion-item *ngFor="let item of Ecvideos.items">
<h2>{{item.snippet.title}}</h2>
</ion-item>
</ion-list>