How to access Object in array using ng-repeat? - arrays

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

Related

Receive data only from the selected item on another page

I would like that when I click on any item in my list, only show the data of this item on the new page. I can already display the items from page 1 to page 2, but I can not filter. Could someone help me with this?
HTML p1
<ion-segment-button value="Todosgastronomia" class="todos-button"
(click)="selecionaprodutoscategoria(1)">
Todos
</ion-segment-button>
<ion-list *ngSwitchCase="'Todosgastronomia'">
<ion-item no-lines *ngFor="let produto of
produtos(click)="querocomprar()" no-padding>
<ion-thumbnail item-start>
<img src="assets/imgs/mmsszjm.png" class="imgast">
</ion-thumbnail>
<ion-row class="rowclass">
<h3 class="nomproduto"> {{produto.nom_produto}} </h3>
<h3 class="nomsubcategoria">{{produto.nom_subcategoria}} </h3>
<h3 class="descproduto"> {{produto.desc_produto}} </h3>
<h3 class="descdesconto"> {{produto.desc_desconto}}</h3>
<h3 class="valproduto">
<font color="#179c90">R$</font> {{produto.val_produto}}
</h3>
<button ion-button small end class="favproduto">
<ion-icon name="icon-ico_favoritos"></ion-icon>
</button>
<button ion-button class="querotodos">QUERO!
</button>
</ion-row>
</ion-item>
</ion-list>
TS p1
export class HomePage implements OnInit {
videoOptions: VideoOptions;
videoUrl: string;
public regioes: Regiao[];
produtos: Produto[];
querocomprar(produto: number) {
this.navCtrl.push(ConteudoprodutoPage, {
val: this.produtos
})
}
TS p2
export class ConteudoprodutoPage {
produto: Produto;
constructor(private payPal: PayPal, public navCtrl: NavController, public
navParams: NavParams) {
this.produto = navParams.get("valor");
}
On your ion-item just pass the produto as a param
<ion-item no-lines *ngFor="let produto of produtos" (click)="querocomprar(produto)" no-padding>
And on your querocomprar() method on HomePage, get the produto item
querocomprar(produto: any) {
this.navCtrl.push(ConteudoprodutoPage, {'val': produto})
}
Receive the val param data on your ConteudoprodutoPage class
constructor(private payPal: PayPal, public navCtrl: NavController, public navParams: NavParams) {
this.produto = navParams.get("val");
}

Ionic 2 Fetching Data From Nested Arrays

I am new to Ionic 2 / Angular 2 and I have been trying to fix a simple issue for an app I am building but have found no solution so far.
I am simply trying to fetch data from a json file to list a number of categories (film titles) and display more detail (production details) into a detail page. The details (director and producer) are nested within an array (production) in the json file.
Although I am able to fetch the film tiles from the json file, I am not able to accesss and display the data from the nested array once the detail page is open.
I have tried a lot of different things (including looping through the array using for Each, creating a production object) but nothing seems to be working. Unless I am missing something very obvious?
Can someone please help?
Thanks in advance! (I will be eternally grateful for any response.)
home.ts
export class HomePage {
films: any;
productions: any;
constructor(public navCtrl: NavController, public http: Http) {
this.films = this.http.get("assets/data/results-data.json").map(res => res.json());
}
openDetails(film) {
this.navCtrl.push('FilmDetailsPage', {film: film});
}
}
home.html
<ion-list>
<button ion-item *ngFor="let film of films.results" (click)="openDetails(film)">
{{ film.title }}
</button>
</ion-list>
results-data.json (extract)
{
"results": [
{
"title": "A New Hope",
"production": [
{
"director" : "George Lucas",
"producer" : "Rick McCallum"
}
]
},
{
"title": "Attack of the Clones",
"production": [
{
"director": "George Lucas",
"producer": "Kurtz"
}
]
},
film-detail.html
<ion-header>
<ion-navbar color="primary">
<ion-title>{{ film.title }}</ion-title> // Working
</ion-navbar>
</ion-header>
<ion-content padding>
<ion-card>
<ion-card-content>
**{{ production.director }} // Not working**
</ion-card-content>
</ion-card>
</ion-content>
film-detail.ts
export class FilmDetailsPage {
film: any;
constructor(public navCtrl: NavController, public navParams: NavParams) {
this.film = this.navParams.get('film');
}
}
Can you try this, I think there is a problem with your path:
film-detail.html
<ion-header>
<ion-navbar color="primary">
<ion-title>{{ film.title }}</ion-title> // Working
</ion-navbar>
</ion-header>
<ion-content padding>
<ion-card>
<ion-card-content>
{{ film.production[0].director }}
</ion-card-content>
</ion-card>
</ion-content>
To make ajax request in angular
this.http.get("assets/data/results-data.json").subscribe(data => {
// Read the result field from the JSON response.
this.films = data['results'];
});
You Should try this:
<ion-content padding>
<ion-card>
<ion-card-content>
{{ film.production[0]?.director }}
</ion-card-content>
</ion-card>
</ion-content>
I was having the same problem but I solved my problem by using the above code. And it renders the html first so that's why error and by using the ?, it will solve the problem.

How to change a particular attribute value in Angular 2 / ionic 2?

So I have this html which dynamically creates cards using the *ngFor
<ion-card *ngFor="let numbers of [0,1,2,3]; let i = index">
<ion-card-content>
<ion-card-title clear>
Card {{i}}
</ion-card-title>
</ion-card-content>
<button ion-button block class="blockbutton" (click)="doSomething(i)">
<ion-icon [name]="iconName" class="plussign"></ion-icon>
<div> Join Room </div>
</button>
</ion-card>
And this is in my .ts
export class FeedPage {
iconName : string;
constructor(public navCtrl: NavController) {
this.iconName = 'add-circle';
}
}
public doSomething(item): void{
console.log(item);
this.iconName = 'checkmark-circle';
}
So this code, on clicking the Block Button, turns all the icons of all the Block Buttons to to checkmark-circle
How do I change only that Particular Button's icon i.e. [name] attribute to checkmark-circle.
I've succeeded in retrieving the index for that element. But how do I modify only that Particular Button ?
Have an array of iconNames.
<ion-icon [name]="iconName[i]" class="plussign"></ion-icon>
In your component side:
public doSomething(item): void{
console.log(item);
this.iconName[item] = 'checkmark-circle';
}
}
You will have to set the entire array depending on the number of cards though.
iconNames:string[]=[];
constructor(public navCtrl: NavController) {
//loop through your card count and push initial value.
iconNames.push(`add-circle`);
}
You should have different icon names for each items in the array.
First maintain an array of objects in your .ts like this:
private _array = [{"iconName" : "name1"},{"iconName" : "name2"}]; // And so on..
Now, in your .html:
<ion-card *ngFor="let numbers of _array let i = index">
<ion-card-content>
<ion-card-title clear>
Card {{i}}
</ion-card-title>
</ion-card-content>
<button ion-button block class="blockbutton" (click)="doSomething(numbers)">
<ion-icon [name]="numbers.iconName" class="plussign"></ion-icon>
<div> Join Room </div>
</button>
</ion-card>
And doSomething() will become:
public doSomething(item): void{
console.log(item);
item.iconName = 'checkmark-circle';
}

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

Observable issue with async pipe

im using a library that help me to sort a list with drag-and-drop.
and the list that im giving it is an Observable of the list type, and then im using async to read it in the html, its very simple and looks like this:
#Injectable()
export class MyCmp implements OnInit {
myList: Observable<MyListType[]>;
showingList = false;
constructor(private _myService: MyService) {
};
public showListData(): void {
this.showingList = true;
this.myList = this._myService.getListData();
}
}
And this is the html:
<button md-button
(click)="showListData()"
title="">Show List
</button>
</div>
<md-content>
<div *ngIf="showingList">
<div dnd-sortable-container [sortableData]="myList | async">
<div class="list-bg" *ngFor="#item of myList | async; #i = index" dnd-sortable [sortableIndex]="i">
ID: {{item.id}} <p></p> Name: {{item.name}}
</div>
</div>
<div>Current List {{myList | async | json}}</div>
</div>
</md-content>
now this does not work, BUT, if I do this in my component instead of myList: Observable<MyListType[]>;
I do:
myList = this._myService.getListData();
and then in the html pass myList it works great...
I dont get it!! drive me crazy :/
please help
getListData() like like this:
public getListData(): Observable<MyListType[]> {
return this._someApiService.getCurrentListData().map(res => res.info);
}

Resources