Ionic 2/3 Pushing items in Array based on ID - ionic-framework

I'm looking to push items from one page to another, based on the category ID. Then I went to push all the contents from the array(who have the category ID that matches) to the next page.
I'm caught between using an if statement to pass the parameters to the second page, or to call the array in the second page and use an NgIf. Below is my code for a better visual. I'm fairly new to Ionic. Thank you for the help!
First Page
if(id = 1) {
category_id: this.referenceList.category_id = 1;
this.navCtrl.push(ReferencePage,{category_id:"category_id"});
}
else {
console.log("nope")
}
Second Page
<div *ngfor = let reference of referenceList></div>
<div *ngif = category.id === 1> {{reference.referenceField1}} {{reference.referenceField2}} {{reference.media}} </div>
Not sure which one to use and why. Thanks again! Happy to clarify if there's any confusion.

You stored the category_id in a variable, so use this:
this.navCtrl.push(ReferencePage,{category_id:category_id});
In the second page controller you need:
import ( NavParams ) from 'ionic-angular';
category_id: number;
constructor(public navParams: NavParams) {
...
}
ionViewDidLoad() {
this.category_id = this.navParams.get('category_id');
}
Also, your html should be (if I understand what you are doing):
<div *ngFor = let reference of referenceList>
<div *ngIf = category_id === 1>
{{reference.referenceField1}};
{{reference.referenceField2}};
{{reference.media}};
</div>
</div>

Related

CDK drag-n-drop auto scroll

I have an Angular 7 app, using CDK Drag-n-Drop to drag and drop rows in a very long list.
What should I do to allow the long list to auto scroll when the dragged item out of the current view?
Any sample code I can refer to?
I have faced the same issue, It happens anytime an outside element is scrollable. This is the open issue - https://github.com/angular/components/issues/16677. - I have slightly modified the solution mentioned in this link.
import { Directive, Input, ElementRef, AfterViewInit } from '#angular/core';
import { CdkDrag } from '#angular/cdk/drag-drop';
#Directive({
selector: '[cdkDrag],[actualContainer]',
})
export class CdkDropListActualContainerDirective {
#Input('actualContainer') actualContainer: string;
originalElement: ElementRef<HTMLElement>;
constructor(cdkDrag: CdkDrag) {
cdkDrag._dragRef.beforeStarted.subscribe( () => {
var cdkDropList = cdkDrag.dropContainer;
if (!this.originalElement) {
this.originalElement = cdkDropList.element;
}
if ( this.actualContainer ) {
const element = this.originalElement.nativeElement.closest(this.actualContainer) as HTMLElement;
cdkDropList._dropListRef.element = element;
cdkDropList.element = new ElementRef<HTMLElement>(element);
} else {
cdkDropList._dropListRef.element = cdkDropList.element.nativeElement;
cdkDropList.element = this.originalElement;
}
});
}
}
Template
<div mat-dialog-content class="column-list">
<div class="column-selector__list">
<div cdkDropList (cdkDropListDropped)="drop($event)">
<div
*ngFor="let column of data"
cdkDrag
actualContainer="div.column-list"
>
</div>
</div>
</div>
</div>
As mentioned here you just need to add cdkScrollable to your list container.

Angular2 default 'selected' select option not being set

I am having an issue getting select boxes on my Angular2 application to show a default option '--please select--' on page load. I have managed to get this working before but I cannot seem to get this working in this particular instance. I'll show my code then explanations as I show it.
Here is my relevant controller code:
import {Component} from "#angular/core";
import {ProductService} from "../../services/product.service";
import {Subscription} from "rxjs";
import {ActivatedRoute} from "#angular/router";
#Component({
selector : 'product',
moduleId : module.id,
templateUrl : '/app/views/products/product-view.html'
})
export class ProductComponent {
private id:number;
private _subscription: Subscription;
public product;
private price;
private quantity = 0;
constructor(
private _productService: ProductService,
private _activatedRoute: ActivatedRoute
) {
}
getProduct(productId: number) {
this._productService.getProduct(productId)
.subscribe((response) => {
response.success.product.options.forEach((option) => {
this[option.name] = {
name: '-- please select --',
product_option_value_id: 0,
price: 0,
price_prefix: '+'
};
option.product_option_value.unshift({
name: '-- please select --',
product_option_value_id: 0,
price: 0,
price_prefix: '+'
});
});
this.product = response.success.product;
this.generatePrice();
});
}
changeOption(optionValueId, option) {
if(optionValueId != 0) {
let selectedOptionValue = option.product_option_value.filter((option) => {
return option.product_option_value_id == optionValueId;
});
this[option.name] = selectedOptionValue[0];
} else {
this[option.name] = {
name: '-- please select --',
product_option_value_id: 0,
price: 0,
price_prefix: '+'
};
}
this.generatePrice();
}
.....
Here I am getting back information about a product which includes 'options' in a form of an array. This array of objects is iterated over to create the select boxes in the view code which will come later. I add a default '-- please select --' object for each option and put it to the front of the array using unshift. I then also set the controller value for this in the line:
this[option.name] = {
name: '-- please select --',
product_option_value_id: 0,
price: 0,
rice_prefix: '+'
};
The relevant view code is as follows:
<div class='product-options'>
<div class='option' *ngFor='let option of product.options; let i = index'>
<p class='option-name' [innerHTML]='option.name'></p>
<select name='option.name' [ngModel]='option.name' (ngModelChange)='changeOption($event, option)' required>
<option *ngFor='let productOptionValue of option.product_option_value; let j = index;' [value]='productOptionValue.product_option_value_id'>{{ productOptionValue.name }}</option>
</select>
</div>
<div class='price' ngDefaultControl [(ngModel)]="price">{{ price | currency:'GBP':true:'1.2-2' }}</div>
<div class='add-to-basket-wrap'>
<button class='add-to-basket'>add to basket</button>
<button class='increment' (click)="changeQuantity('down')">-</button>
<input type='text' name='quantity-to-add' [(ngModel)]="quantity" (click)='addToBasket()' />
<button class='increment'(click)="changeQuantity('up')">+</button>
</div>
</div>
Here I loop through the options then through the values for these options to generate the select boxes. I set the [ngModel] attribute for the select to the same as the one that was saved in my controller. I was under the impression that Angular2 would detect this binding, spot the value was the same as the controller value and then automatically set that as the 'selected' default option.
Can anyone see why this isn't working?
Thanks
Looks like your code is not working because your template and your class are not binding to the same properties.
In your component template, when you write this:
<div *ngFor="let option of product.options; let i = index">
<select [ngModel]="option.name">...</select>
</div>
... you're effectively binding each <select> to a class property named product.options[i].name.
On the other hand, in your component class, when you write this:
changeOption(optionValueId, option) {
this[option.name] = selectedOptionValue[0];
}
... you're writing to a class property named after whatever string is contained in option.name, e.g. foo.
As you can see, product.options[i].name and foo don't match. Even by changing foo to another string, you won't be able to access the property you want.
A few remarks/questions that might help:
It's a bit strange to store options inside "dynamic" class properties — this[option.name] = .... Why not store them in a dedicated this.options property that you can declare, type, and log out for debugging purposes: this.options[option.name] = ....
Why did you decide to use <select [ngModel]="..." (ngModelChange)="..."> vs the more compact <select [(ngModel)]="...">?
Any reason why you're using simple quotes on your HTML attributes, e.g. <div class='price'> vs <div class="price">? This is not the usual style.

Angular 2: Is there an easy way using FormBuilder with FormArray in ng2?

Situation
I'm working on a form where I want to list some mails having a checkbox besides the subject and a "check all" checkbox in the same column as the other checkboxes.
The form looks simply like this:
[ ] Check all
------------------------------------------
[ ] This is email subject #1
[ ] This is email subject #2
[ ] ...
When I select Check all all the below checkboxes should be selected and when I click again, all mails should be unselected.
The mails are coming dynamically into the component via an #Input and the list can change at any point of time.
So far so easy, nothing special. BUT it seems not so easy when using the FormBuilder in ng2 for that. Side note: I want to use the FormBuilder to test my code less end-to-end but more with unit tests.
Current code
Template
<form [formGroup]="form">
<div><input formControlName="toggleAll" type="checkbox"></div>
<div>
<ul formArrayName="checkMailList">
<li *ngFor="let mail of mails; let i=index">
<input type="checkbox" [formControlName]="i">
<div>mail.subject</div>
</li>
</ul>
</div>
</form>
Component
#Component({ ... })
export class MailListComponent implements OnChanges {
#Input() mails: Mail[];
private get checkMailList(): FormArray { return this.form.get('checkMailList') as FormArray; }
constructor(private fb: FormBuilder) {
this.form = this.fb.group({
checkMailList: this.fb.array([]);
});
}
ngOnChanges(changes: SimpleChanges) {
if (!changes['mails'] || !changes['mails'].currentValue) {
return;
}
// remove array first from form, as we will get
// mails again when anything updates
if (this.checkMailList.length > 0) {
this.form.removeControl('checkMailList');
this.form.addControl('checkMailList', this.fb.array([]));
}
this.mails.forEach(m => {
this.checkMailList.push(this.fb.control());
});
this.form
.valueChanges
.pluck('toggleAll')
.distinctUntilChanged()
.subscribe(selectAll => {
if (selectAll) {
this.checkMailList.setValue(this.mails.map(_ => true));
} else {
this.checkMailList.reset();
}
});
}
}
Problem
I think that there could occur a race condition/timing issue: I iterate over the mails array provided by #Input but I wire the checkMailList manually in the template to the corresponding index. I iterate over all mails whenever the #Input changes. I don't know if Angular first iterates over all mails in the template and then runs the ngOnChange method or vice versa. Can anyone can give me a profounded answer here?
Forms are the fundamental part of every WebApp. Am I doing it right? Any help would be appreciated.

Ionic Master Detail view with Firebase auto-generated child key returning JSON $value null

I am new to Ionic and Firebase. While fetching data for details view I am getting undefined value for $scope.program.
However, I have fetched the complete programs list in Master view. Clicking the list item from master view returns index (0, 1, 2, etc) of the list in console log but not the child key (which I was expecting)
During my research, I found out this question quite relevant to my problem, by Wes Haq. But while implementing the same, it has no change in the result. Please help.
From the above question by Wes Haq, I couldn't find the state provider details. I may be missing something there. Thanks in advance to all.
controllers.js
.controller('myServicesCtrl', ['$scope', '$state', '$stateParams', '$ionicActionSheet', 'AgencyProgService',
function ($scope, $state, $stateParams, $ionicActionSheet, AgencyProgService) {
//Only items relative to the logged/signed in Agency shall be pushed to the scope.items
$scope.programs = AgencyProgService.getPrograms();
}])
.controller('serviceDetailCtrl', ['$scope', '$stateParams', 'AgencyProgService',
function ($scope, $stateParams, AgencyProgService) {
AgencyProgService.getProgram($stateParams.index).then(function (program) {
$scope.program = program;
});
console.log("serviceDetailCtrl: scope.program is: " + $scope.program);
}])
service.js
.service('AgencyProgService', ['$q', '$firebaseArray', '$firebaseObject', 'AgencyDataService', function ($q, $firebaseArray, $firebaseObject, AgencyDataService) {
var ref = firebase.database().ref().child('programs/'); // this is a valid ref with https://my-demo.firebaseio.com/programs
var agencyIDfromPrograms = AgencyDataService.getAgencyUID();
var refFilter = ref.orderByChild("agencyID").equalTo(agencyIDfromPrograms);
return {
getPrograms: function () {
return $firebaseArray(refFilter);
},
getProgram: function (programId) {
console.log("getProgram: ID is: " + programId + "And refFilter to use is: " + ref);
var deferred = $q.defer();
var programRef = ref.child(programId); // here programId should be the autogenerated child key from fire DB "programs"
var program = $firebaseObject(programRef);
deferred.resolve(program);
return deferred.promise;
}
}
}])
Views:
myServices.html
<ion-list id="myServices-list9">
<ion-item id="myServices-list-item11"
ng-repeat="item in programs" ui- sref="serviceDetail({index: $index})">
<div class="item-thumbnail-left">
<i class="icon"></i>
<h2>{{item.progName}} </h2>
<p>{{item.servType}} for: {{item.servHours}}</p>
<p>From: {{item.servStartDate}}</p>
</div>
</ion-item>
</ion-list>
serviceDetail.html
<div class="list card">
<div class="item item-avatar">
<img src="{{item.user.picture.thumbnail}} " />
<h1>{{program.servContact}}</h1>
<h2>{{program.$id}} {{program.progName}}</h2>
<p>{{item.servContact}} {{item.servStartDate}}</p>
</div>
<pre> {{program | json}} </pre>
From serviceDetail view, no data from program is visible, as you can see from the screen shot below. List card for serviceDetail. on clicking 2nd item on myServices, it shows this detail screen with $id as 1. Expected is the child key for programs:
Firebase data structure screenshot for child programs is as below,
Appreciate your suggestions.

Class prefix as selector for each function

I am able to do this using an ID prefix as the selector, but I need to be able to do it with classes instead. It's an each function for opening up different modal windows on the same page. I need to avoid using ID names because I have some modal windows that will have multiple links on the same page, and when using IDs, only the first link will work.
So here's the function as it works with IDs:
$('div[id^=ssfamodal-help-]').each(function() {
var sfx = this.id,
mdl = $(this),
lnk = $('.link-' + sfx),
cls = $('.ssfamodal-close'),
con = $('.ssfamodal-content');
lnk.click(function(){
mdl.show();
});
cls.click(function(){
mdl.hide();
});
mdl.click(function() {
mdl.hide();
});
con.click(function() {
return false;
});
});
and I'm trying to change it to classes instead, like:
$('div[class^=ssfamodal-help-]').each(function() {
var sfx = this.attr('class'),
etc.
But I cannot get it to work without using IDs. Is it possible?
EDIT Fixed error with semi-colon at end of Vars, and updated Fiddle with the fix. Still not working though.
Here's a Fiddle
** UPDATE **
To be clearer, I need to be able to refer to the same modal more than once on the same page. E.g.:
MODAL 1
MODAL 2
MODAL 3
MODAL 4
LINK TO MODAL 1
LINK TO MODAL 2
LINK TO MODAL 3
LINK TO MODAL 4
OTHER STUFF
LINK TO MODAL 1
LINK TO MODAL 4
LINK TO MODAL 3
OTHER STUFF
LINK TO MODAL 2
ETC.
When using classes get rid of the ID habit :
className1, className2, className3 ... etc
simply use
className
HTML:
<div class="ssfamodal-help-base ssfamodal-backdrop">
<div id="help-content" class="ssfamodal-content">
<span class="ssfamodal-close">[x]</span>
Howdy
</div>
</div>
<div class="ssfamodal-help-base ssfamodal-backdrop">
<div id="help-content" class="ssfamodal-content">
<span class="ssfamodal-close">[x]</span>
Howdy Ho
</div>
</div>
<span class="link-ssfamodal-help-base">One</span>
<span class="link-ssfamodal-help-base">Two</span>
LIVE DEMO
var $btn = $('.link-ssfamodal-help-base'),
$mod = $('.ssfamodal-help-base'),
$X = $('.ssfamodal-close');
$btn.click(function(i) {
var i = $('[class^="link-"]').index(this); // all .link-** but get the index of this!
// Why that?! cause if you only do:
// var i = $('.link-ssfamodal-help-base').index();
// you'll get // 2
// cause that element, inside a parent is the 3rd element
// but retargeting it's index using $('className').index(this);
// you'll get the correct index for that class name!
$('.ssfamodal-help-base').eq(i).show() // Show the referenced element by .eq()
.siblings('.ssfamodal-help-base').hide(); // hide all other elements (with same class)
});
$X.click(function(){
$(this).closest('.ssfamodal-help-base').hide();
});
From the DOCS:
http://api.jquery.com/eq/
http://api.jquery.com/index/
http://api.jquery.com/closest/
Here I created a quite basic example on how you can create a jQuery plugin of your own to handle modals: http://jsbin.com/ulUPIje/1/edit
feel free to use and abuse.
The problem is that class attributes can consist of many classes, rather than IDs which only have one value. One solution, which isn't exactly clean, but seems to work is the following.
$('div').filter(function () {
var classes = $(this).attr('class').split(/\s+/);
for (var i = 0; i < classes.length; i++)
if (classes[i].indexOf('ssfamodal-help-') == 0)
return true;
return false;
}).each(function() {
// code
});
jsFiddle
Or, equivalently
$('div').filter(function () {
return $(this).attr('class').split(/\s+/).some(function (e) {
return e.indexOf('ssfamodal-help-') == 0;
});
}).each(function() {
// code
});
jsFiddle
If there is one-to-one relationship between the modal helps and the modal links which it appears there is...can simplfy needing to match class values by using indexing.
For this reason you don't need unique class names, rather they just overcomplicate things. Following assumes classes stay unique however
var $helps=$('div[id^=ssfamodal-help-]');
var $help_links=$('div[id^=link-ssfamodal-help-]');
$help_links.click(function(){
var linkIndex= $help_links.index(this);
$helps.hide().eq( linkIndex ).show();
});
/* not sure if this is what's wanted, but appeared original code had it*/
$helps.click(function(){
$(this).hide()
})
/* close buttons using traverse*/
$('.ssfamodal-close').click(function(){
$(this).closest('div[id^=ssfamodal-help-]' ).hide();
});
Also believe that this code is a little more readable than original apporach
DEMO
Can you try this,
$('div[class^=ssfamodal-help-]').each(function() {
var sfx = $(this).attr('class');
console.log(sfx);
/*console log:
ssfamodal-help-base ssfamodal-backdrop
ssfamodal-help-base2 ssfamodal-backdrop
*/
});
Demo: http://jsfiddle.net/xAssR/51/
why don't you write like
$('div.classname').each(function() {
// you can write your desired code here
var sfx = this.attr('class');
var aa= this.attr('id');
});
or
$('.classname').each(function() {
// you can write your desired code here
var sfx = this.attr('class');
var aa= this.attr('id');
});
where classname is the name of the class used for the div in html
Thanks.