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

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

Related

Angular Filtering: Problem when Clearing Search Box

I Have a list of objects that i'm displaying, and i added a search box to filter a column, now when i enter a value, it works fine and the data is filtered.
The problem is, when i clear the search box, i don't get all the data back, i stay stuck with what i searched first, so i have to refresh every time i want to change the entered value or get the whole list.
Here's my Ts Code :
export class AdherentsComponent implements OnInit {
adherents: adherent[];
name: string;
constructor(private adherentService: AdherentService, private alertify: AlertifyService) { }
ngOnInit() {
this.getAdherents();
this.name = "";
}
getAdherents() {
this.adherentService.getAdherents().subscribe((
adherents: adherent[]) => {
this.adherents = adherents;
}, error => { this.alertify.error(error); })
}
Search() {
if (this.name.length > 0) {
this.adherents = this.adherents.filter(res => {
return res.nomcomplet.toLowerCase().match(this.name.toLowerCase());
})
}
else if (this.name.length === 0) {
this.adherents = this.adherents;
console.log(this.adherents.length);
}
}
}
Here's my Html Code :
<body >
<main role="main" class="container" >
<div class="jumbotron" style="background-color: white;">
<h2>Liste des Adhérents</h2>
<input type="text" [(ngModel)]="name" (input)="Search()" />
<table class="table table-hover">
<thead class="thead-light">
<tr>
<th>Nom Complet</th>
<th>Grade</th>
<th>Poste</th>
<th>Telephone</th>
<th>E-mail</th>
<th></th>
</tr>
</thead>
<tr *ngFor="let item of adherents">
<td>{{item.nomcomplet}}</td>
<td>{{item.grade}}</td>
<td>{{item.poste}}</td>
<td>{{item.telephone}}</td>
<td>{{item.email}}</td>
<td><button [routerLink]="['/adherents/', item.id]" style="margin-right: 0.2em;" title="Details" class="btn-sm btn-secondary text-white"><i class="fa fa-eye"></i></button>
<button [routerLink]="['/adherentEdit/', item.id]"
style="margin-right: 0.2em;" title="Modifier" class="btn-sm btn-primary text-white"><i class="fa fa-edit"></i></button></td>
</tr>
</table>
</div>
</main>
</body>
Please how can i modify The Search() Function so i can dynamically get data from the Array when changing the value in the search box input ?
Use a different variable for all the values and another one for the values that are displayed to the user. When you search you filter all elements and save them into the array that you are using to display to the user. Same occurs when you clear searchbox, simply get all values and save them to this array.
You are replacing the value in the property _adherents that contains all the values with a new value.
Instead you could
make _adherents private.
Create another property current_adherents that represents an array of your filtered/sorted output.
Use current_adherents in your template.
example code
export class AdherentsComponent implements OnInit {
private _adherents: adherent[];
public current_adherents: adherent[];
name: string;
// removed code irrelevant to the question
Search() {
this.current_adherents = this._adherents.filter(res => {
return res.nomcomplet.toLowerCase().match(this.name.toLowerCase());
})
}
}
Edit: if name is an empty string by definition it will match all elements. So you could remove your if/else logic too ;).

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

Get into Firebase complex object containing another object

I've got Angular2 project connected directly with Firebase.
The structure of my database is presented in the picture below. So we've got couple of objects.
Main is orders, then the key od order, some extra information and another object "items" which contains several objects like 0, 1 etc. Each of them has a object called "product" which has some other parameters...
orders
-> datePlaced,
items
-> 0
-> quantity, totalPrice, product
->
imageUrl,
price,
title
My point is that when I'm creating "My Orders" tab, I'd like to get information of every item in specific order e.g. I see list of orders, and small button "View order", I click and I see details about this order with special key.
I prepared view with orders, buttons but I cannot take any objects form object orders, I've got a blank page.
order-details.component.ts
export class OrderDetailsComponent implements OnInit, OnDestroy {
order$;
userId: string;
userSubscription: Subscription;
constructor(private orderService: OrderService, private authService: AuthService) {}
async ngOnInit() {
this.userSubscription = this.authService.user$.subscribe(user => this.userId = user.uid);
this.order$ = this.authService.user$.switchMap(u => this.orderService.getOrdersByUser(u.uid));
}
ngOnDestroy() {
this.userSubscription.unsubscribe();
}
}
order-details.component.html
<div class="card" *ngIf="order$ | async as order">
<div class="card-body">
<h5 class="card-title">Your Order</h5>
<p class="card-text">You ordered {{ order.datePlaced | date }} items</p>
<ul class="list-group list-group-flush">
<li *ngFor="let order of order.shipping" class="list-group-item">
{{ order.city }} x {{ order.city }}
<div class="float-right">
{{ order.totalPrice | currency:'USD':'symbol' }}
</div>
</li>
<li class="list-group-item font-weight-bold">
Total
<div class="float-right">
{{ order.totalPrice | currency:'USD':'symbol' }}
</div>
</li>
</ul>
</div>
</div>
order.service.ts
export class OrderService {
constructor(private db: AngularFireDatabase, private shoppingCartService: ShoppingCartService) { }
async placeOrder(order) {
let result = await this.db.list('/orders').push(order);
this.shoppingCartService.clearCart();
return result;
}
getOrders() {
return this.db.list('/orders');
}
getOrdersByUser(userId: string) {
return this.db.list('/orders', {
query: {
orderByChild: 'userId',
equalTo: userId
}
});
}
}
How can I get every parameter from complex object "orders"?
I solved this by taking param routes in my order-details.component.ts and then a create function getOrder(id) in order service. When you have id of your order it's quite simple to take object from database.

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

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