ng-model binded to the field doesn't work - angularjs

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 = [];

Related

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

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.

Creating select all checkbox in VueJS trough loop

I've created some data that are displayed trough a loop as table.
That code seems fine, however in my methods I get an error 'page is not defined'.
Does anyone know how do I define it?
Table:
<tr v-for="page in pages" v-bind:key="page">
<td>
<input type="checkbox" v-model="pageIds" #click="select" :value="page.id">
</td>
<td>{{page.name}}</td>
<td>
<v-tooltip bottom>
<template v-slot:activator="{ on, attrs }">
<span v-bind="attrs" v-on="on"
><v-icon class="icon delete">mdi-delete</v-icon></span
>
</template>
<span>Delete Page</span>
</v-tooltip>
</td>
</tr>
Methods:
<script>
export default {
data: () => ({
pages: [
{"id":"/","name":"/"},
{"id":"/index","name":"/index"},
{"id":"/about-us","name":"/about-us"}
],
selected: [],
allSelected: false,
pageIds: []
}),
methods: {
selectAll: function() {
this.pageIds = [];
if (this.allSelected) {
for (page in this.pages) {
this.pageIds.push(this.pages[page].id.toString());
}
}
},
select: function() {
this.allSelected = false;
}
}
};
</script>
change this in your code. it will resolve your error
from
v-for="page in pages" v-bind:key="page"
to
v-for="(page, index) in pages"
v-bind:key="index"

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 access Object in array using ng-repeat?

i´m having a problem with using ng-repeat. I´m using Ionic 2 with TypeScript and HTML5. I created an array of Objects where i need to access it´s attributes. It´s saying "cannot read property c.getAttribute of undefined" but when i tried to access these attributes not using ng-repeat (just typing array[0].getAttribute), everything worked fine.
Here is my code:
<ion-list>
<ion-item ng-repeat="c in card">
<ion-card class="styledRow">
<ion-item class="cardHeaderClass">
<font size="4" style="color:#FFFFFF;">{{c.getExpiration}}</font>
<p>Monthly student</p>
</ion-item>
<ion-item class="rangeSlider">
<p style="color:white">Perm</p>
<ion-badge color="blue" item-right>{{c.getPermValue}}/{{c.getTotalValue}}{{c.getDayEuro}}
</ion-badge>
</ion-item>
<ion-item class="rangeSlider">
<ion-range disabled="false" min="0" max="{{c.getTotalValue}}" step="1" [(ngModel)]="c.getPermValue" color="secondary">
<ion-icon range-left name="close" color="danger"></ion-icon>
<ion-icon range-right name="checkmark-circle-outline" color="secondary"></ion-icon>
</ion-range>
</ion-item>
<ion-row class="styledRow">
<ion-col>
<button ion-button icon-left color="#f4f4f4" clear small>
<ion-icon name="calendar"></ion-icon>
<div>Platnosť: {{c.getExpiration}}</div>
</button>
</ion-col>
</ion-row>
<div text-right="" class="styledRow">
<ion-note>Refreshed: 12.3.2017
</ion-note>
</div>
</ion-card>
</ion-item>
</ion-list>
And here is my typescript:
export class HomePage {
card: permCard[];
constructor(public navCtrl: NavController) {
this.card = new Array();
for (let i = 0; i < 2; i++){
this.card.push(new permCard("Name","Name", 33, 40, " "+"days", "12.2.2017"));
}
}
}
export class permCard{
private centerName: string;
private permName: string;
private permValue: number;
private totalValue: number;
private dayEuro: string;
private expiration: string;
constructor(public center_name: string, public perm_name: string, public perm_value: number, public total_value: number,
public day_euro: string, public expiration_date: string){
this.centerName = center_name;
this.permName = perm_name;
this.permValue = perm_value;
this.totalValue = total_value;
this.dayEuro = day_euro;
this.expiration = expiration_date;
}
get getCenterName(): string {
return this.centerName;
}
get getPermValue(): number {
return this.permValue;
}
get getPermName(): string {
return this.permName;
}
get getTotalValue(): number {
return this.totalValue;
}
get getDayEuro(): string {
return this.dayEuro;
}
get getExpiration(): string {
return this.expiration;
}
}
I don´t know, if the problem is in the array, but only the array.push worked for me for initialization of array. Please, do you have any idea, what should be the problem. TypeScript and angular is new for me, thanks.
how-to-access-object-in-array-using-ng-repeat
You cant. ng-repeat is angularjs (version 1) syntax.
Ionic 2 is built on top of angular 2.
The format for for loop in template is:
<ion-item *ngFor="let c of card">
<ion-card class="styledRow">
<!-- shortened for brevity -->
</ion-item>
Documentation ngFor

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