Get value from each *ngFor ionic 4, ionic 5, ionic 6 - angularjs

I have the following code:
<ion-item *ngFor="let box of boxes">
This will show results from array:
On the .ts file i have the following:
isApproved : boolean;
public box: any;
This will generate from boxes array:
box1 -> [id, name, isApproved]
box2 -> [id, name, isApproved]
box3 ->[id, name, isApproved]
I need to get the isApproved value of each box, so when i activate the toggle, isApproved will change in database.
I know one method that doesn't fits my needs, like clicking and getting the id from route but i want to open a new page for that.

Just put and ngModel in the ion-toggle:
html:
<ion-item *ngFor="let box of boxes">
<ion-avatar slot="start"></ion-avatar>
<ion-label>...</ion-label>
<ion-toggle [(ngModel)]="box.isApproved" (ionChange)="approvedToggled($event)"></ion-toggle>
</ion-item>
ts:
approvedToggled(event, box) {
if(event.detail.value) {
// save to box to database
}
/* or:
if(item.isApproved) {
// save to database
}
*/
}

The solution is very simple.
The working code is:
On my HTML:
<div *ngFor="let box of boxes">
<ion-item-sliding id="anyId">
<ion-item>
<ion-avatar slot="start">
<img [offset]="100" [alt]="box.user?.name"
defaultImage="./assets/img/photo.png" [lazyLoad]="box.user?.photo?.url()" />
</ion-avatar>
<ion-label class="ion-text-wrap">
<ion-text color="dark">
<h3 class="bold no-margin">
{{ box.user?.name }}
</h3>
</ion-text>
</ion-label>
</ion-item>
<ion-item-options side="end">
<ion-item-option color="primary" (click)="onDelete(box)">
<ion-icon slot="icon-only" name="trash"></ion-icon>
</ion-item-option>
</ion-item-options>
</ion-item-sliding>
</div>
On my TS i have:
Importing service:
import { Box } from '../../services/box-service';
Before constructor:
public boxes: Box[] = [];
public box: Box;
constructor(private BoxService: Box) {
super(injector);
}
Loading boxes from service:
async loadDataFromService() {
try {
const boxes = await this.boxService.loadBoxes(this.params);
for (let box of boxes) {
this.boxes.push(box);
}
this.onRefreshComplete(boxes);
} catch {
}
}
... this will return an array with arrays. Each array has an object.
Now we just access each box from HTML (click)="onDelete(box)"
async onDelete(box: Box) {
await Swal.fire({
title: 'Are you sure?',
text: 'Blah, blah',
icon: 'warning',
iconColor: '#5038de',
showCancelButton: true,
confirmButtonColor: '#5038de',
cancelButtonColor: '#e0b500',
confirmButtonText: 'Yes',
cancelButtonText: 'No',
heightAuto: false,
showClass: {
popup: 'animated fade-in'
},
hideClass: {
popup: 'animated fade-out'
}
}).then(async (result) => {
if (result.value) {
await this.boxService.deleteBox(box)
this.goTo()
} else {
this.goTo()
}
});
}
}
Resuming, the solution for:
<ion-item *ngFor="let box of boxes">
<ion-avatar slot="start"></ion-avatar>
<ion-label>...</ion-label>
<ion-toggle (ionChange)="myFunction(box)"></ion-toggle>
</ion-item>
was simply (ionChange)="myFunction(box)" or (click)="myFunction(box)"
In my case box will be an entire object, passing the id will be enough to perform any action.

Related

ionic 2 local storage get and display the data

hi i cant access my data in localstorage , it always gives me error . i need help in displaying my datas in my home . thank you for your help :)
Error:
Typescript Error
Argument of type 'Promise' is not assignable to parameter of type 'string'.
this.user = JSON.parse(this.storage.get(this.key));
prompt.present();
Typescript
import { Component } from '#angular/core';
import { IonicPage, NavController, NavParams, ViewController, AlertController } from 'ionic-angular';
import {Storage} from '#ionic/storage';
/**
* Generated class for the CrudPage page.
*
* See http://ionicframework.com/docs/components/#navigation for more info
* on Ionic pages and navigation.
*/
#IonicPage()
#Component({
selector: 'page-crud',
templateUrl: 'crud.html',
})
export class CrudPage {
user: any = [] ;
key: any;
constructor(public navCtrl: NavController,
public navParams: NavParams,
public viewCtrl: ViewController,
public alertCtrl: AlertController,
public storage: Storage) {
this.storage.forEach( (value) => {
this.user.push(value);
});
}
ionViewDidLoad() {
console.log('ionViewDidLoad CrudPage');
}
add() {
let prompt = this.alertCtrl.create({
title: 'Add User',
message: "Enter information of the user",
inputs: [
{
name: 'name',
placeholder: 'name'
},
{
name: 'password',
placeholder: 'password'
},
],
buttons: [
{
text: 'Cancel',
handler: data => {
console.log('Cancel clicked!');
}
},
{
text: 'Save',
handler: data => {
let key = data.name + data.password;
this.storage.set(key, JSON.stringify(data));
console.log(data);
}
}
]
});
this.user = JSON.parse(this.storage.get(this.key));
prompt.present();
}
delete(key){
this.storage.remove(key);
}
update(key){
}
}
HTML
<!--
Generated template for the CrudPage page.
See http://ionicframework.com/docs/components/#navigation for more info on
Ionic pages and navigation.
-->
<ion-header>
<ion-navbar>
<ion-title>Crud</ion-title>
</ion-navbar>
</ion-header>
<ion-content padding>
<button ion-button clear icon-start color="dark" (click)="add()">
<ion-icon name="add-circle">Add User</ion-icon>
</button>
<br>
<ion-grid text-center>
<ion-row>
<ion-col width-100>
USERS
</ion-col>
</ion-row>
<ion-row>
<ion-col width-33>
<strong>User Name</strong>
</ion-col>
<ion-col width-33>
<strong>Password</strong>
</ion-col>
<ion-col width-33>
<strong>Action</strong>
</ion-col>
</ion-row>
<ion-row *ngFor="let users of user" text-center>
<ion-col width-33>
<p>{{users.name}}</p>
</ion-col>
<ion-col width-33>
<p>{{users.password}}</p>
</ion-col>
<ion-col width-33>
<button ion-button clear icon-start color="dark" (click)="delete(users.name+users.password)">
<ion-icon name="trash"></ion-icon>
</button>
<button ion-button clear icon-start color="dark" (click)="update(users.name+users.password)">
<ion-icon name="create"></ion-icon>
</button>
</ion-col>
</ion-row>
</ion-grid>
</ion-content>
Please help :) Thank you very much :)
this.storage.get(this.key) returns a promise, you have to do that:
this.storage.get(this.key).then(value => {
this.user = JSON.parse(value);
});
https://ionicframework.com/docs/storage/

How to retrieve data from a multi level object in Ionic 3?

This page works likes the following. The user selects a product (C2, Coca Cola, etc.) then the prices from the different supermarket are supposed to be displayed. This is the object I created.
productPrices = [
{
name: "C2 Green Tea",
prices: [
{
smPrice: 19.15,
tsPrice: 19.25,
rbPrice: 19.10
}
],
stock: 50
},
{
name: "Coca Cola",
prices: [
{
smPrice: 21.50,
tsPrice: 21.45,
rbPrice: 24.50
}
],
stock: 50
},
{
name: "Nature's Spring",
prices: [
{
smPrice: 12.50,
tsPrice: 11.50,
rbPrice: 13.00
}
],
stock: 50
},
{
name: "Red Horse Beer",
prices: [
{
smPrice: 31.50,
tsPrice: 29.50,
rbPrice: 30.90
}
],
stock: 50
},
];
getProductPrice(product: string){
return this.productPrices.filter(item => item.name == product);
}
By using the getProducPrice() method, I'm able to get the product selected and its properties. But I can't get the value of the prices. What I have on the template page is this.
<div *ngFor="let itemPrice of productPrices">
<div *ngFor="let marketPrice of itemPrice.prices">
<form (ngSubmit)="onFormSubmit(userForm)" #userForm="ngForm" >
<ion-list>
<ion-list-header>
Supermarkets
</ion-list-header>
<ion-item>
<ion-thumbnail item-start>
<img src="assets/grocery/market-logo/ts.jpg">
</ion-thumbnail>
<p>{{marketPrice.tsPrice}}</p>
<button ion-button clear item-end (click)="onBuy()" >Buy</button>
</ion-item>
<ion-item>
<ion-thumbnail item-start>
<img src="assets/grocery/market-logo/sm.png">
</ion-thumbnail>
<p>{{marketPrice.smPrice}}</p>
<button ion-button clear item-end (click)="onBuy()"> Buy</button>
</ion-item>
<ion-item>
<ion-thumbnail item-start>
<img src="assets/grocery/market-logo/rb.jpg">
</ion-thumbnail>
₱<input name="price" value="{{marketPrice.rbPrice}}">
<p>{{marketPrice.rbPrice}}</p>
<button ion-button clear item-end (click)="onBuy()">Buy</button>
</ion-item>
<ion-item>
<ion-label>Enter Quantity</ion-label>
<ion-input type="number" min="0"></ion-input>
</ion-item>
</ion-list>
</form>
</div>
</div>
The problem with that is that if I use a form to submit, it'll submit all the values including the prices of the other supermarkets.
Is there a better way for me to loop from the object I received and access the prices values of each product? I'm not using a DB nor is this file saved in a json file. I just want to know if there's a better way to get values at the typescript file by using some methods. Thank you.
try this you will property of selected product
<div *ngFor="let item of productPrices">
<button (click) ="getProductPrice(item)">get</button>
</div>
In your ts file
getProductPrice(product: any){
console.log(product);
}

ng-model binded to the field doesn't work

Using ng-model I wanted to bind fields with the array object this.enhancements[item.id] = { checked: false, qty: 0 }; so whenever the checkbox is checked or input field has some values it will automatically get filled into the array object.
The following is the code I am currently working with. Please advise what am I doing wrong.
home.ts
export class HomePage {
extras: any;
enhancements: any;
constructor(public navCtrl: NavController, public http: Http) {
this.http.get('https://www.example.com/api/enhance/11/?format=json').map(res => res.json()).subscribe(response => {
this.extras = response.Extras;
this.enhancements = {};
this.extras.forEach(item => {
this.enhancements[item.id] = { checked: false, qty: 0 };
})
});
}
onChange(){
console.log( this.enhancements );
}
}
home.html
<ion-content padding>
<ion-grid>
<ion-row *ngFor="let item of extras" id="booking-enhancements-wrap-{{ item.id }}">
<ion-col width-10>
<ion-checkbox (ionChange)="onChange()" ng-model="enhancements[item.id].checked" ng-checked="enhancements[item.id].checked"></ion-checkbox>
</ion-col>
<ion-col width-70>{{ item.name }}</ion-col>
<ion-col width-20><input type="number " id="qty-{{ item.id }} " style="width: 100%; " (input)="onChange()" ng-model="enhancements[item.id].qty" /></ion-col>
</ion-row>=
</ion-grid>
</ion-content>
If you are using ionic2 Then you can't use ng-model
You have to use [(ngModel)]
see https://ionicframework.com/docs/v2/api/components/checkbox/Checkbox/
try this
replace
this.enhancements = {};
to
this.enhancements = [];

How to make filter to be viewed in html

On my home page I added a button named 'city'. On clicking it opens a popup listing the city names. On clicking the city 'paris' the data with city name must be displayed.
homepage
<ion-header-bar class="bar bar-subheader">
<button class="button button-flat button-positive"ng-click="citypopup();" style="padding-right: 63px;
padding-left: 18px;">
<l >City </l>
<l class="icon ion-chevron-down"></l>
</button>
</ion-header-bar>
<ion-content>
<div class='card ' ng-repeat="item in list | filter:test.searchCity ">
<div class="list " >
<div class='item' style="padding-top:0px;" > {{item.id}}
<l class="item-icon-right" style="padding-left:30%"> {{item.date}} </l>
</div>
<div class='item' style="padding-top:0px;" >{{item.status }}
<l class="item-icon-right" style="text-align:right;">{{item.QCstatus}}</l>
<i class="icon ion-chevron-right"></i>
</div>
<b class='item '> {{item.Factory}} </b>
<l class='item '>{{item.city }}</l>
</div>
popup page
<ion-list>
<ul class="list" ng-model="test.searchCity" ng-repeat="ci in cityList | orderBy:'city' " >
<li class="item" ng-click="test.searchCity">{{ci.city}} </li>
</ul>
</ion-list>
javascript
$scope.test = {
searchCity: null,
};
$scope.cityList = [
{
"city": "Chennai"
}, {
"city": "Banglore"
}, {
"city": "Delhi"
}
];
$scope.list = [
{
id: "#001",
date:"DEC 04 2016",
status: "Successful",
QCstatus: "Approve",
Factory: "ARUN ICE CREAM",
city: "paris"
},
{
id: "#002",
date: "JAN 11 2016",
status: "Successful",
QCstatus: "Approve",
Factory: "Floxtronics",
city: "Delhi"
},
{
id: "#003",
date: "Feb 14 2016",
status: "Bug fixing",
QCstatus: "Approve",
Factory: "Aachi",
city: "Chennai"
}
];
$scope.$watch('test.searchCity', function () {
$scope.test.searchCity = null;
console.log('test.searchCity')
});
$scope.citypopup = function() {
var myPopup = $ionicPopup.show({
scope: $scope,
templateUrl: 'templates/cityTemplate.html',
buttons: [
{ text: 'Cancel',
type: 'button-positive' },
]
});
}
What I need is when I click 'city' button, my city popup appears and when I click on a city nothing happens! Could someone help me?
No need to create another popup page, you can open popup content in citypopup() function
$scope.citypopup = function() {
$scope.popup = $ionicPopup.show({
template:"<ion-list><ul class='list' ng-model='test.searchCity' ng-repeat='ci in cityList | orderBy:city ' ><li class='item' ng-click='searchCity(ci.city)'>{{ci.city}} </li> </ul></ion-list>" ,
title: 'City',
scope: $scope
});
}
$scope.searchCity = function(city){
$scope.test.searchCity = city;
$scope.popup.close();
}
You never assign test.searchCity.
In you popup page code you use ng-click="test.searchCity", where you probably should use ng-click="test.searchCity = ci.city".
Unrelated to your problem (but a matter of correct use of patterns): No need for ngModel in a ul element (it's only for form elements), and ng-repeat makes more sense when used on lis rather than uls.
In conclusion:
<ion-list>
<ul class="list">
<li class="item" ng-repeat="ci in cityList | orderBy:'city' " ng-click="test.searchCity = ci.city">{{ci.city}} </li>
</ul>
</ion-list>

how get the list of selected items in angular.js

Here I am using angular.js to show a list of people
<div class="recipient" ng-repeat="person in people">
<img src="{{person.img}}" /> person.name
<div class="email">person.email</div>
</div>
$scope.people = [{id:1}, {id:2}, {id:3}, {id:4}];
The looks is like below
What I want to do is I can select multiple items and by click a OK button, I can get a list of selected items. so If I select id 1 and id 2, then I want to get return a list of [{id:1},{id:2}]
How could I implement it in angular.js
Well I guess that if you're looping through a collection of people using a ng-repeat, you could add the ng-click directive on each item to toggle a property of you're object, let's say selected.
Then on the click on your OK button, you can filter all the people that have the selected property set to true.
Here's the code snippet of the implementation :
<div class="recipient" ng-repeat="person in people" ng-click="selectPeople(person)">
<img src="{{person.img}}" /> person.name
<div class="email">person.email</div>
</div>
<button ng-click="result()">OK</button>
function demo($scope) {
$scope.ui = {};
$scope.people = [{
name: 'Janis',
selected: false
}, {
name: 'Danyl',
selected: false
}, {
name: 'tymeJV',
selected: false
}];
$scope.selectPeople = function(people) {
people.selected = !people.selected;
};
$scope.result = function() {
$scope.ui.result = [];
angular.forEach($scope.people, function(value) {
if (value.selected) {
$scope.ui.result.push(value);
}
});
};
}
.recipient {
cursor: pointer;
}
.select {
color:green;
}
.recipient:hover {
background-color:blue;
}
<script src="https://code.angularjs.org/1.2.25/angular.js"></script>
<div ng-app ng-controller="demo">
<div class="recipient" ng-repeat="person in people" ng-click="selectPeople(person)" ng-class="{ select: person.selected }">
<div class="name">{{ person.name }}</div>
</div>
<button ng-click="result()">OK</button>
Result :
<ul>
<li ng-repeat="item in ui.result">{{ item.name }}</li>
</ul>
</div>
If you only want to show checked or unchecked you could just apply a filter, but you would need to toggle the filter value from undefined to true if you didn't wan't to get stuck not being able to show all again.
HTML:
<button ng-click="filterChecked()">Filter checked: {{ checked }}</button>
<div class="recipient" ng-repeat="person in people | filter:checked">
<input type='checkbox' ng-model="person.isChecked" />
<img ng-src="{{person.img}}" />{{ person.name }}
<div class="email">{{ person.email }}</div>
</div>
Controller:
// Apply a filter that shows either checked or all
$scope.filterChecked = function () {
// if set to true or false it will show checked or not checked
// you would need a reset filter button or something to get all again
$scope.checked = ($scope.checked) ? undefined : true;
}
If you want to get all that have been checked and submit as form data you could simply loop through the array:
Controller:
// Get a list of who is checked or not
$scope.getChecked = function () {
var peopleChkd = [];
for (var i = 0, l = $scope.people.length; i < l; i++) {
if ($scope.people[i].isChecked) {
peopleChkd.push(angular.copy($scope.people[i]));
// Remove the 'isChecked' so we don't have any DB conflicts
delete peopleChkd[i].isChecked;
}
}
// Do whatever with those checked
// while leaving the initial array alone
console.log('peopleChkd', peopleChkd);
};
Check out my fiddle here
Notice that person.isChecked is only added in the HTML.

Resources