ngx-gallery not display image - angular7

Angular 7 ngx-gallery
I was able to take data in json format without any errors, but ngx-gallery doesn't seem, it loaded in the element in the page details but the images and the ngx-gallery template do not appear ,
It may not be taking photos from the service, but didn't make a mistake,
here is my code :
import {
NgxGalleryOptions,
NgxGalleryImage,
NgxGalleryAnimation
} from "ngx-gallery";
#Component({
selector: "app-city-detail",
templateUrl: "./city-detail.component.html",
styleUrls: ["./city-detail.component.css"],
providers: [CityService]
})
export class CityDetailComponent implements OnInit {
constructor(
private activatedRoute: ActivatedRoute,
private cityService: CityService
) {}
city: City;
photos: Photo[] = []
galleryOptions: NgxGalleryOptions[];
galleryImages: NgxGalleryImage[];
ngOnInit() {
this.activatedRoute.params.subscribe(params => {
this.getCityById(params["cityId"]);
});
}
getCityById(cityId) {
this.cityService.getCityById(cityId).subscribe(data => {
this.city = data;
this.getPhotosByCity(cityId)
});
}
getPhotosByCity(cityId){
this.cityService.getPhotosByCity(cityId).subscribe(data=>{
this.photos = data;
this.setGallery();
})
}
getImages(){
const imageUrls= []
for(let i = 0;i<this.city.photos.length;i++){
imageUrls.push({
small:this.city.photos[i].url,
medium:this.city.photos[i].url,
big:this.city.photos[i].url
})
}
return imageUrls;
}
setGallery(){
this.galleryOptions = [
{
width: '100%',
height: '400px',
thumbnailsColumns: 4,
imageAnimation: NgxGalleryAnimation.Slide
},
// max-width 800
{
breakpoint: 800,
width: '100%',
height: '600px',
imagePercent: 80,
thumbnailsPercent: 20,
thumbnailsMargin: 20,
thumbnailMargin: 20
},
// max-width 400
{
breakpoint: 400,
preview: false
}
];
this.galleryImages = this.getImages()
}
}
Template:
<ngx-gallery *ngIf="galleryImages" [options]="galleryOptions" [images]="galleryImages"></ngx-gallery>

this tutorial is complete
https://github.com/lukasz-galka/ngx-gallery-demo/blob/master/src/app/app.component.ts
use method addImage for your problem
help this image
private loadAll() {
this.imageService.getAllImage).subscribe(result => {
this.addImage(result);
});
}
addImage(images: any[]): void
images.forEach(image=>{
this.onlyPreviewExample.images.push(this.getImage(this.getRandomInt(1,2),doc));
});
}
private getImage(index: number, image?: any): NgxGalleryImage {
return {
big: 'imageUrl'
}
}
private getImages(): NgxGalleryImage[] {
let images = new Array<NgxGalleryImage>();
return images;
}
private getRandomInt(min: number, max: number) {
return Math.floor(Math.random() * (max - min + 1)) + min;
}
ngOnInit() {
this.ngxGalleryModel = new Array<NgxGalleryModel>();
this.ngxGalleryModel.push(
this.onlyPreviewExample = new NgxGalleryModel('Only preview', this.getImages(), [{
image: false,
thumbnails: false,
previewCloseOnClick: true,
previewCloseOnEsc: true,
previewZoom: true,
previewRotate: true,
// previewDownload: true,
previewFullscreen: true,
previewKeyboardNavigation: true,
arrowNextIcon: "fa fa-arrow-left",
arrowPrevIcon: "fa fa-arrow-right",
fullscreenIcon: "fa fa-arrows-alt",
width: '0px',
height: '0px'
}])
)
}
#ViewChild('onlyPreviewGallery', {static: false}) onlyPreviewGallery: NgxGalleryComponent;
ngxGalleryModel: NgxGalleryModel[];
onlyPreviewExample: NgxGalleryModel;

Related

Ng2-Charts Unexpected change chart's color when data is changed

In my project I use ng2-charts. All works fine and chart is shown as expected (data, labels, chart's colors), but when data is changed then color of chart become grey by default. May someone help to correct problem with chart's color?
Here is my code:
import { ChartDataSets } from 'chart.js';
import { Color, Label } from 'ng2-charts';
...
export class JuridicalBidPrimaryComponent extends BidComponent {
lineChartData: ChartDataSets[];
lineChartLabels: Label[];
lineChartLegend = true;
lineChartType = 'line';
lineChartColors: Color[] = [
{
backgroundColor: 'rgba(148,159,177,0.2)',
borderColor: 'rgba(148,159,177,1)'
},
{
backgroundColor: 'rgba(77,83,96,0.2)',
borderColor: 'rgba(77,83,96,1)'
}];
options: any = {
legend: { position: 'bottom' }
}
constructor(
...//inject services
) {
super();
this.initData();
};
initData(): void {
this.lineChartData = [];
this.lineChartLabels = [];
if (this.cabinetId)
this.getData(this.year);
}
getData(year: number) {
this.isLoading = true;
var limitPromise = this.juridicalLimitService.getPrimary(this.cabinetId, year).catch(error => {
this.notificationService.error(error);
return Observable.throw(error);
});
var analyticsPromise = this.juridicalAnalyticsService.getUsedEnergy(this.cabinetId, year).catch(error => {
this.notificationService.error(error);
return Observable.throw(error);
});
forkJoin([limitPromise, analyticsPromise]).subscribe(data => {
this.limits = data[0];
this.lineChartLabels = data[1].map(e => e.Period);
this.lineChartData.push(
{
data: data[1].map(e => e.Limit),
label: 'Bid'
},
{
data: data[1].map(e => e.Used),
label: 'Used'
}
);
this.isLoading = false;
}, error => {
this.isLoading = false;
});
}
}
export abstract class BidComponent {
cabinetId: number;
isLoading: boolean = false;
#Input("periods") periods: BaseDictionary[];
#Input("cabinetId") set CabinetId(cabinetId: number) {
this.cabinetId = cabinetId;
this.initData();
}
abstract initData(): void;
}
As you can see this component is partial and I use setter to listen of cabinetId changes.
Here is html part:
...
<canvas baseChart width="400" height="150"
[options]="options"
[datasets]="lineChartData"
[labels]="lineChartLabels"
[legend]="lineChartLegend"
[chartType]="lineChartType"
[colors]="lineChartColors"></canvas>
...
And I use this component as:
<app-juridical-bid-primary [cabinetId]="cabinetId"></app-juridical-bid-primary>
I find similar question similar question, but, unfortunately, don't understand answer
After some hours of code testing I find answer. It is needed to correct code from question:
...
import * as _ from 'lodash'; //-- useful library
export class JuridicalBidPrimaryComponent extends BidComponent {
lineChartData: ChartDataSets[] = [];
lineChartLabels: Label[] = [];
...
initData(): void {
/*this.lineChartData = [];
this.lineChartLabels = [];*/ //-- this lines is needed to remove
if (this.cabinetId)
this.getData(this.year);
}
getData(year: number) {
...
forkJoin([limitPromise, analyticsPromise]).subscribe(data => {
this.limits = data[0];
this.lineChartLabels.length = 0;
this.lineChartLabels.push(...data[1].map(e => e.Period));
if (_.isEmpty(this.lineChartData)) {
//-- If data array is empty, then we add data series
this.lineChartData.push(
{
data: data[1].map(e => e.Limit),
label: 'Замовлені величини'
},
{
data: data[1].map(e => e.Used),
label: 'Використано'
}
);
} else {
//-- If we have already added data series then we only change data in data series
this.lineChartData[0].data = data[1].map(e => e.Limit);
this.lineChartData[1].data = data[1].map(e => e.Used);
}
this.isLoading = false;
}, error => {
this.isLoading = false;
});
}
}
As I understand ng2-charts, if we clean dataset (lineChartData) and add new data then the library understand this as create new series and don't use primary settings for the ones. So we have to use previous created series.
I hope it will be useful for anyone who will have such problem as I have.

I want to apply search and date range filter simultaneously in material data table in angular 7

I want to apply a filter for the whole search and date range filter for material data table in angular 7.
I know that filter and filter predicate cannot be used together, but please tell me if there is an alternative.
I have already implemented the dynamic whole table search filter and now I wanted to filter the data source table with a date range. So, I implemented the filter predicate with that. But, now my whole search filter is not working.
import { Component, OnInit, ViewChild } from '#angular/core';
import * as Chartist from 'chartist';
import { ActivatedRoute } from '#angular/router';
import { MatPaginator, MatTableDataSource, MatSort } from '#angular/material';
import { FormGroup, FormControl } from '#angular/forms';
#Component({
selector: 'app-seller',
templateUrl: './seller.component.html',
styleUrls: ['./seller.component.css']
})
export class SellerComponent implements OnInit {
public state_name: any;
displayedColumns: string[] = ['position', 'id', 'date', 'name', 'address', 'city', 'state', 'amount'];
// tslint:disable-next-line: no-use-before-declare
dataSource = new MatTableDataSource(ELEMENT_DATA);
filterForm = new FormGroup({
fromDate: new FormControl(),
toDate: new FormControl(),
});
get fromDate() { return this.filterForm.get('fromDate').value; }
get toDate() { return this.filterForm.get('toDate').value; }
#ViewChild(MatPaginator) paginator: MatPaginator;
#ViewChild(MatSort) sort: MatSort;
constructor( private route: ActivatedRoute) {
this.dataSource.filterPredicate = (data) => {
if (this.fromDate && this.toDate) {
return new Date(data.date).getTime() >= this.fromDate.getTime() && new Date(data.date).getTime() <= this.toDate.getTime();
}
return true;
}
}
startAnimationForLineChart(chart: any) {
let seq: any, delays: any, durations: any;
seq = 0;
delays = 80;
durations = 500;
chart.on('draw', function(data: any) {
if (data.type === 'line' || data.type === 'area') {
data.element.animate({
d: {
begin: 600,
dur: 700,
from: data.path.clone().scale(1, 0).translate(0, data.chartRect.height()).stringify(),
to: data.path.clone().stringify(),
easing: Chartist.Svg.Easing.easeOutQuint
}
});
} else if (data.type === 'point') {
seq++;
data.element.animate({
opacity: {
begin: seq * delays,
dur: durations,
from: 0,
to: 1,
easing: 'ease'
}
});
}
});
seq = 0;
};
ngOnInit() {
// Initialize the chart
const dataCompletedTasksChart: any = {
labels: ['M', 'T', 'W', 'T', 'F', 'S', 'S'],
series: [
[230, 750, 450, 300, 280, 240, 200, 190]
]
};
const optionsCompletedTasksChart: any = {
lineSmooth: Chartist.Interpolation.cardinal({
tension: 0
}),
low: 0,
high: 1000,
chartPadding: { top: 0, right: 0, bottom: 0, left: 0}
}
const completedTasksChart = new Chartist.Line('#completedTasksChart', dataCompletedTasksChart, optionsCompletedTasksChart);
this.startAnimationForLineChart(completedTasksChart);
// Get state name from url
const name = this.route.snapshot.paramMap.get('state');
this.state_name = name;
// Initialize the pagination
this.dataSource.paginator = this.paginator;
// Initialize the sorting
this.dataSource.sort = this.sort;
}
// // Gets the total amount of all transactions
// getTotalAmount() {
// // tslint:disable-next-line: no-use-before-declare
// return ELEMENT_DATA.map(t => t.amount).reduce((acc, value) => acc + value, 0);
// }
// Whole table search filter
applySearchFilter(filterValue: string) {
this.dataSource.filter = filterValue.trim().toLowerCase();
}
// DateRange filter
applyDateFilter() {
this.dataSource.filter = '' + Math.random();
}
}
export interface PeriodicElement {
position: number;
id: any;
date: any;
name: string;
address: any;
city: string;
state: string;
amount: any;
}
const ELEMENT_DATA: any[] = [];
for (let i = 1; i <= 100; i++) {
const data = {
position: i,
id: 'QWERTY' + (i * 2),
date: '04/' + (i + 1) + '/2019',
name: 'Joshi Chemist',
address: 'W-980/8, Sainik Farm, New Delhi-110062',
city: 'New Delhi',
state: 'DELHI',
amount: i * 2300
};
ELEMENT_DATA.push(data);
}
Both the filter working simultaneously.

Camera doesn't work after compilation

I use Ionic Framework.
Camera works perfectly in Ionic View. But it doesn't work after compilitaion on iOS.
Please, help to find out what is the problem.
Camera code in services.js:
app.factory('FileService', function() {
var images;
var IMAGE_STORAGE_KEY = 'dav-images';
function getImages() {
var img = window.localStorage.getItem(IMAGE_STORAGE_KEY);
if (img) {
images = JSON.parse(img);
} else {
images = [];
}
return images;
};
function addImage(img) {
images.push(img);
window.localStorage.setItem(IMAGE_STORAGE_KEY, JSON.stringify(images));
};
return {
storeImage: addImage,
images: getImages
}
});
app.factory('ImageService', function($cordovaCamera, FileService, $q, $cordovaFile) {
function optionsForType(type) {
var source;
switch (type) {
case 0:
source = Camera.PictureSourceType.CAMERA;
break;
case 1:
source = Camera.PictureSourceType.PHOTOLIBRARY;
break;
}
return {
quality: 90,
destinationType: Camera.DestinationType.DATA_URL,
sourceType: source,
allowEdit: false,
encodingType: Camera.EncodingType.JPEG,
popoverOptions: CameraPopoverOptions,
saveToPhotoAlbum: false,
correctOrientation:true
};
}
function saveMedia(type) {
return $q(function(resolve, reject) {
var options = optionsForType(type);
$cordovaCamera.getPicture(options).then(function(imageBase64) {
FileService.storeImage(imageBase64);
});
})
}
return {
handleMediaDialog: saveMedia
}
});
Camera code in controllers.js:
app.controller('CameraController', function($scope, $cordovaDevice, $cordovaFile, $ionicPlatform, $cordovaEmailComposer, $ionicActionSheet, ImageService, FileService) {
$ionicPlatform.ready(function() {
$scope.images = FileService.images();
$scope.$apply();
});
$scope.addMedia = function() {
$scope.hideSheet = $ionicActionSheet.show({
buttons: [
{ text: 'Take photo' },
{ text: 'Photo from library' }
],
titleText: 'Add images',
cancelText: 'Cancel',
buttonClicked: function(index) {
$scope.addImage(index);
}
});
}
$scope.addImage = function(type) {
$scope.hideSheet();
ImageService.handleMediaDialog(type).then(function() {
$scope.$apply();
});
}
$scope.sendEmail = function() {
if ($scope.images != null && $scope.images.length > 0) {
var mailImages = [];
var savedImages = $scope.images;
for (var i = 0; i < savedImages.length; i++) {
mailImages.push('base64:attachment'+i+'.jpg//' + savedImages[i]);
}
$scope.openMailComposer(mailImages);
}
}
$scope.openMailComposer = function(attachments) {
var bodyText = '<html><h2>My Images</h2></html>';
var email = {
to: '',
attachments: attachments,
subject: 'Devdactic Images',
body: bodyText,
isHtml: true
};
$cordovaEmailComposer.open(email, function(){
console.log('email view dismissed');
}, this);
}
});
To resolve this problem you need to compile an app with XCode.
After XCode compilation camera works correctly.
Probably, the problem with camera was caused by Ionic compilation.

How to access Customer table's data in nopcommerce

I want to show Customer table's data of nopcommerce in admin page.
i did write a plugin for that and receive data in controller but in view i have a problem and show me error happened message.
here is my controller code:
public class UserDetailsController : BasePluginController
{
private ICustomerService _UserDetail;
public UserDetailsController(ICustomerService UserDetail)
{
_UserDetail = UserDetail;
}
public ActionResult Manage()
{
return View();
}
[HttpPost]
public ActionResult GetUsers(DataSourceRequest userDetail)
{
var details = _UserDetail.GetAllCustomers();
var gridModel = new DataSourceResult
{
Data = details,
Total = details.Count
};
return Json(gridModel);
}
}
And this is my view code:
#{
Layout = "~/Views/Shared/_AdminLayout.cshtml";
}
<script>
$(document).ready(function() {
$("#user-details").kendoGrid({
dataSource: {
type: "json",
transport: {
read: {
url: "#Html.Raw(Url.Action("GetUsers", "UserDetails"))",
type: "POST",
dataType: "json",
},
},
schema: {
data: "Data",
total: "Total",
errors: "Errors",
model: {
id: "Id",
}
},
requestEnd: function(e) {
if (e.type == "update") {
this.read();
}
},
error: function(e) {
display_kendoui_grid_error(e);
// Cancel the changes
this.cancelChanges();
},
serverPaging: true,
serverFiltering: true,
serverSorting: true
},
pageable: {
refresh: true,
numeric: false,
previousNext: false,
info:false
},
editable: {
confirmation: true,
mode: "inline"
},
scrollable: false,
columns: [
{
field: "Email",
title: "User Name",
width: 200
},
{
command: [
{
name: "edit",
text: "#T("Admin.Common.Edit")"
}, {
name: "destroy",
text: "#T("Admin.Common.Delete")"
}
],
width: 200
}
]
});
});
</script>
<div id="user-details"></div>
can anybody help me?
Change your GetUsers method on this way:
var details = _UserDetail.GetAllCustomers();
var gridModel = new DataSourceResult
{
Data=details.Select(x=>
{
return new UserDetail()
{
Email= x.Email
};
}),
Total = details.Count(),
};
return Json(gridModel);

Google Combo Charts?

I have 4 entities and I show them for 4 days. But first and last days I cant see other 2 entities.In 3 August I cant see T0,T1. In 6 August I cant see T2,T3.
Codes
var evalledData = eval("(" + result.chartData + ")");
var ac = new google.visualization.ComboChart($("#chart_div_ay").get(0));
ac.draw(new google.visualization.DataTable(evalledData, 0.5), {
//title: 'Son 7 günlük sayaç okumalarının toplamı.',
width: '100%',
height: 300,
vAxis: { title: "kW" },
hAxis: { title: "Gün" },
seriesType: "bars",
series: { 5: { type: "line"} }
});
Controller:
public ActionResult MusteriSayaclariOkumalariChartDataTable(DateTime startDate, DateTime endDate, int? musteri_id)
{
IEnumerable<TblSayacOkumalari> sayac_okumalari = entity.TblSayacOkumalari;
var sonuc = from s in sayac_okumalari
where s.TblSayaclar.musteri_id == musteri_id && s.okuma_tarihi.Value >= startDate && s.okuma_tarihi.Value <= endDate
group s by new { date = new DateTime(((DateTime)s.okuma_tarihi).Year, ((DateTime)s.okuma_tarihi).Month, ((DateTime)s.okuma_tarihi).Day) } into g
select new
{
okuma_tarihi = g.Key,
T1 = g.Sum(x => x.kullanim_T1) / 1000,
T2 = g.Sum(x => x.kullanim_T2) / 1000,
T3 = g.Sum(x => x.kullanim_T3) / 1000,
T4 = g.Sum(x => x.kullanim_T0) / 1000
};
//Get your data table from DB or other source
DataTable chartTable = new DataTable();
chartTable.Columns.Add("Tarih").DataType = System.Type.GetType("System.DateTime");
chartTable.Columns.Add("T1").DataType = System.Type.GetType("System.Double");
chartTable.Columns.Add("T2").DataType = System.Type.GetType("System.Double");
chartTable.Columns.Add("T3").DataType = System.Type.GetType("System.Double");
chartTable.Columns.Add("Toplam").DataType = System.Type.GetType("System.Double");
foreach (var item in sonuc)
{
chartTable.Rows.Add(item.okuma_tarihi.date, item.T1.Value, item.T2.Value, item.T3.Value, item.T4.Value);
}
//convert datetime value to google datetype, if your first column is date
Bortosky
.Google
.Visualization
.GoogleDataTable
.SetGoogleDateType(chartTable.Columns["Tarih"],
Bortosky.Google.Visualization.GoogleDateType.Date);
//convert DataTable to GoogleDataTable
var googleDataTable =
new Bortosky.Google.Visualization.GoogleDataTable(chartTable);
//Pass the google datatable to UI as json string
return new JsonResult
{
Data = new
{
success = true,
chartData = googleDataTable.GetJson()
},
JsonRequestBehavior = JsonRequestBehavior.AllowGet
};
}
This action return json as google examples custom data.
evalledData output:
Is there any option about this problem?
Thanks.
I recently had to build a chart like this. Please consider my code for your solution:
Put this in your Controller:
<EmployeeAuthorize()>
Function WeightAreaChartData() As JsonResult
Dim myData = db.Tbl_Weights.Where(Function(x) x.Weight_Employee_ID).OrderBy(Function(x) x.Weight_Create_Date)
Dim data = New List(Of Object)
data.Add(New Object() {"Date", "Your Weight"})
For Each i As Tbl_Weight In myData
data.Add(New Object() {DateTime.Parse(i.Weight_Create_Date).Day, i.Weight_Amount})
Next
Return Json(data, JsonRequestBehavior.AllowGet)
End Function
Put this in your view; changing the $.post() URL accordingly:
<script type="text/javascript">
google.load("visualization", "1", { packages: ["corechart"] });
google.setOnLoadCallback(drawChart);
function drawChart() {
$.post('/Weight/WeightAreaChartData', {},
function (data) {
var tdata = new google.visualization.arrayToDataTable(data);
var options = {
title: 'Weight Lost & Gained This Month',
hAxis: { title: 'Day of Month', titleTextStyle: { color: '#1E4A08'} },
vAxis: { title: 'Lbs.', titleTextStyle: { color: '#1E4A08'} },
chartArea: { left: 50, top: 30, width: "75%" },
colors: ['#FF8100']
};
var chart = new google.visualization.ColumnChart(document.getElementById('chart_div'));
chart.draw(tdata, options);
});
}
</script>
<div id="chart_div" style="width: 580px; height: 200px;"></div>
To fix your specific issue of the bars being cut off, I believe you can use this in your options:
hAxis: {
viewWindowMode: 'pretty'
}
Like this:
var options = {
title: 'Weight Lost & Gained This Month',
hAxis: { title: 'Day of Month', titleTextStyle: { color: '#1E4A08'} },
vAxis: { title: 'Lbs.', titleTextStyle: { color: '#1E4A08' } },
chartArea: { left: 50, top: 30, width: "75%" },
colors: ['#FF8100', 'blue'],
hAxis: {
viewWindowMode: 'pretty'
}
};

Resources