//long-press.directive.d.ts
import { ElementRef, EventEmitter, OnDestroy, OnInit, NgZone } from '#angular/core';
import { Gesture } from 'ionic-angular/gestures/gesture';
export declare class LongPressDirective implements OnInit, OnDestroy {
zone: NgZone;
interval: number;
onPressStart: EventEmitter<any>;
onPressing: EventEmitter<any>;
onPressEnd: EventEmitter<any>;
el: HTMLElement;
pressGesture: Gesture;
int: any;
constructor(zone: NgZone, el: ElementRef);
ngOnInit(): void;
ngOnDestroy(): void;
}
//long-press.drective.js
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
var core_1 = require("#angular/core");
var gesture_1 = require("ionic-angular/gestures/gesture");
var LongPressDirective = (function () {
function LongPressDirective(zone, el) {
this.zone = zone;
this.onPressStart = new core_1.EventEmitter();
this.onPressing = new core_1.EventEmitter();
this.onPressEnd = new core_1.EventEmitter();
this.el = el.nativeElement;
}
LongPressDirective.prototype.ngOnInit = function () {
var _this = this;
if (!this.interval)
this.interval = 500;
if (this.interval < 40) {
throw new Error('A limit of 40ms is imposed so you don\'t destroy device performance. If you need less than a 40ms interval, please file an issue explaining your use case.');
}
this.pressGesture = new gesture_1.Gesture(this.el);
this.pressGesture.listen();
this.pressGesture.on('press', function (e) {
_this.onPressStart.emit(e);
_this.zone.run(function () {
_this.int = setInterval(function () {
_this.onPressing.emit();
}, _this.interval);
});
});
this.pressGesture.on('pressup', function (e) {
_this.zone.run(function () {
clearInterval(_this.int);
});
_this.onPressEnd.emit();
});
};
LongPressDirective.prototype.ngOnDestroy = function () {
var _this = this;
this.zone.run(function () {
clearInterval(_this.int);
});
this.onPressEnd.emit();
this.pressGesture.destroy();
};
return LongPressDirective;
}());
LongPressDirective.decorators = [
{ type: core_1.Directive, args: [{
selector: '[ion-long-press]'
},] },
];
/** #nocollapse */
LongPressDirective.ctorParameters = function () { return [
{ type: core_1.NgZone, },
{ type: core_1.ElementRef, },
]; };
LongPressDirective.propDecorators = {
'interval': [{ type: core_1.Input },],
'onPressStart': [{ type: core_1.Output },],
'onPressing': [{ type: core_1.Output },],
'onPressEnd': [{ type: core_1.Output },],
};
exports.LongPressDirective = LongPressDirective;
//# sourceMappingURL=long-press.directive.js.map
This is implementation of 'press', 'press-up' event.
This directive intends to build upon the existing Hammer.JS press event that Ionic uses for long pressing, by giving you interval emission.
https://www.npmjs.com/package/ionic-long-press
I want to add 'drag'-'drop' event.
I am beginner of angular.
Expert's help is needed.
Thanks.
I solved the problem using this plugin.
https://github.com/AbineshSrishti/ionic2-selection-card-drag
Related
I'm brand new to Angular and typescript and still trying to make it through but now I can't.
I bought a template for Angular (VEX) and I would like to integrate data from firebase into a datatable already present in the template.
In the template, this table is fed by static data and I would like to replace that with my call to firebase.
I am really lost and I would like to understand how I can do to get there.
Here is the manage-users-component.ts
import { AfterViewInit, Component, Input, OnInit, ViewChild } from '#angular/core';
import { Observable, of, ReplaySubject } from 'rxjs';
import { filter } from 'rxjs/operators';
import { Customer } from './interfaces/customer.model';
import { MatTableDataSource } from '#angular/material/table';
import { MatPaginator } from '#angular/material/paginator';
import { MatSort } from '#angular/material/sort';
import { MatDialog } from '#angular/material/dialog';
import { TableColumn } from '../../../#vex/interfaces/table-column.interface';
import { aioTableData, aioTableLabels } from '../../static-data/aio-table-data';
import { CustomerCreateUpdateComponent } from './customer-create-update/customer-create-update.component';
import icEdit from '#iconify/icons-ic/twotone-edit';
import icDelete from '#iconify/icons-ic/twotone-delete';
import icSearch from '#iconify/icons-ic/twotone-search';
import icAdd from '#iconify/icons-ic/twotone-add';
import icFilterList from '#iconify/icons-ic/twotone-filter-list';
import { SelectionModel } from '#angular/cdk/collections';
import icMoreHoriz from '#iconify/icons-ic/twotone-more-horiz';
import icFolder from '#iconify/icons-ic/twotone-folder';
import { fadeInUp400ms } from '../../../#vex/animations/fade-in-up.animation';
import { MAT_FORM_FIELD_DEFAULT_OPTIONS, MatFormFieldDefaultOptions } from '#angular/material/form-field';
import { stagger40ms } from '../../../#vex/animations/stagger.animation';
import { FormControl } from '#angular/forms';
import { UntilDestroy, untilDestroyed } from '#ngneat/until-destroy';
import { MatSelectChange } from '#angular/material/select';
import icPhone from '#iconify/icons-ic/twotone-phone';
import icMail from '#iconify/icons-ic/twotone-mail';
import icMap from '#iconify/icons-ic/twotone-map';
import firebase from 'firebase';
import { UserManageService } from '../../services/user-manage.service';
#UntilDestroy()
#Component({
selector: 'vex-manage-users',
templateUrl: './manage-users.component.html',
styleUrls: ['./manage-users.component.scss'],
animations: [
fadeInUp400ms,
stagger40ms
],
providers: [
{
provide: MAT_FORM_FIELD_DEFAULT_OPTIONS,
useValue: {
appearance: 'standard'
} as MatFormFieldDefaultOptions
}
]
})
export class ManageUsersComponent implements OnInit, AfterViewInit {
layoutCtrl = new FormControl('boxed');
/**
* Simulating a service with HTTP that returns Observables
* You probably want to remove this and do all requests in a service with HTTP
*/
subject$: ReplaySubject<Customer[]> = new ReplaySubject<Customer[]>(1);
data$: Observable<Customer[]> = this.subject$.asObservable();
customers: Customer[];
#Input()
columns: TableColumn<Customer>[] = [
{ label: 'Checkbox', property: 'checkbox', type: 'checkbox', visible: true },
{ label: 'ShipTo', property: 'extId', type: 'text', visible: true },
{ label: 'uid', property: 'uid', type: 'text', visible: true },
{ label: 'Compagny', property: 'compagny', type: 'text', visible: true },
{ label: 'Name', property: 'name', type: 'text', visible: true, cssClasses: ['font-medium'] },
{ label: 'First Name', property: 'firstName', type: 'text', visible: false },
{ label: 'Last Name', property: 'lastName', type: 'text', visible: false },
{ label: 'Email', property: 'email', type: 'text', visible: true },
{ label: 'Phone', property: 'phone', type: 'text', visible: true },
{ label: 'Role', property: 'role', type: 'text', visible: true },
{ label: 'Actions', property: 'actions', type: 'button', visible: true }
];
pageSize = 10;
pageSizeOptions: number[] = [5, 10, 20, 50];
dataSource: MatTableDataSource<Customer> | null;
selection = new SelectionModel<Customer>(true, []);
searchCtrl = new FormControl();
labels = aioTableLabels;
icPhone = icPhone;
icMail = icMail;
icMap = icMap;
icEdit = icEdit;
icSearch = icSearch;
icDelete = icDelete;
icAdd = icAdd;
icFilterList = icFilterList;
icMoreHoriz = icMoreHoriz;
icFolder = icFolder;
#ViewChild(MatPaginator, { static: true }) paginator: MatPaginator;
#ViewChild(MatSort, { static: true }) sort: MatSort;
constructor(private dialog: MatDialog,
private usersManageService: UserManageService ) {
}
get visibleColumns() {
return this.columns.filter(column => column.visible).map(column => column.property);
}
/**
* Example on how to get data and pass it to the table - usually you would want a dedicated service with a HTTP request for this
* We are simulating this request here.
*/
getData() {
return of(aioTableData.map(customer => new Customer(customer)));
}
ngOnInit() {
const users = this.usersManageService.getUsers();
console.log(users);
this.getData().subscribe(customers => {
this.subject$.next(customers);
});
console.log(aioTableData);
this.dataSource = new MatTableDataSource();
this.data$.pipe(
filter<Customer[]>(Boolean)
).subscribe(customers => {
this.customers = customers;
this.dataSource.data = customers;
});
this.searchCtrl.valueChanges.pipe(
untilDestroyed(this)
).subscribe(value => this.onFilterChange(value));
}
ngAfterViewInit() {
this.dataSource.paginator = this.paginator;
this.dataSource.sort = this.sort;
}
createCustomer() {
this.dialog.open(CustomerCreateUpdateComponent).afterClosed().subscribe((customer: Customer) => {
/**
* Customer is the updated customer (if the user pressed Save - otherwise it's null)
*/
if (customer) {
/**
* Here we are updating our local array.
* You would probably make an HTTP request here.
*/
this.customers.unshift(new Customer(customer));
this.subject$.next(this.customers);
}
});
}
updateCustomer(customer: Customer) {
this.dialog.open(CustomerCreateUpdateComponent, {
data: customer
}).afterClosed().subscribe(updatedCustomer => {
/**
* Customer is the updated customer (if the user pressed Save - otherwise it's null)
*/
if (updatedCustomer) {
/**
* Here we are updating our local array.
* You would probably make an HTTP request here.
*/
const index = this.customers.findIndex((existingCustomer) => existingCustomer.uid === updatedCustomer.uid);
this.customers[index] = new Customer(updatedCustomer);
this.subject$.next(this.customers);
}
});
}
deleteCustomer(customer: Customer) {
/**
* Here we are updating our local array.
* You would probably make an HTTP request here.
*/
this.customers.splice(this.customers.findIndex((existingCustomer) => existingCustomer.uid === customer.uid), 1);
this.selection.deselect(customer);
this.subject$.next(this.customers);
}
deleteCustomers(customers: Customer[]) {
/**
* Here we are updating our local array.
* You would probably make an HTTP request here.
*/
customers.forEach(c => this.deleteCustomer(c));
}
onFilterChange(value: string) {
if (!this.dataSource) {
return;
}
value = value.trim();
value = value.toLowerCase();
this.dataSource.filter = value;
}
toggleColumnVisibility(column, event) {
event.stopPropagation();
event.stopImmediatePropagation();
column.visible = !column.visible;
}
/** Whether the number of selected elements matches the total number of rows. */
isAllSelected() {
const numSelected = this.selection.selected.length;
const numRows = this.dataSource.data.length;
return numSelected === numRows;
}
/** Selects all rows if they are not all selected; otherwise clear selection. */
masterToggle() {
this.isAllSelected() ?
this.selection.clear() :
this.dataSource.data.forEach(row => this.selection.select(row));
}
trackByProperty<T>(index: number, column: TableColumn<T>) {
return column.property;
}
// onLabelChange(change: MatSelectChange, row: Customer) {
// const index = this.customers.findIndex(c => c === row);
// this.customers[index].labels = change.value;
// this.subject$.next(this.customers);
// }
}
Here is the Firebase Realtime database "users" that I would like to insert in my datatable
Here is the function I imaginated for do the job but I dont know where to put it into
getUsers() {
firebase.database().ref('/users').once('value').then((snapshot) => {
const users = snapshot.val();
return users;
});
}
I am completely stuck and I thank very much in advance anyone who can help me.
I made some progress in my case and I was able to recover the values I wanted.
The array returned by my function matches the array of the example template.
getData() {
const users = [];
firebase.database().ref('/users').once('value').then((snapshot) => {
users.push(snapshot.val()) ;
const users2 = users[0];
const mapped = Object.keys(users2).map(key => (users2[key]));
console.log(mapped.map(customer => new Customer(customer)));
// console.log(aioTableData.map(customer => new Customer(customer)));
return of(mapped.map(customer => new Customer(customer)));
});
// return of(aioTableData.map(customer => new Customer(customer)));
The problem is that in ngOnInit, when the call to the function is done, it expects a subscribe and I don't know how to do it.
ngOnInit() {
this.getData().subscribe(customers => {
this.subject$.next(customers);
});
this.dataSource = new MatTableDataSource();
this.data$.pipe(
filter<Customer[]>(Boolean)
).subscribe(customers => {
this.customers = customers;
this.dataSource.data = customers;
});
this.searchCtrl.valueChanges.pipe(
untilDestroyed(this)
).subscribe(value => this.onFilterChange(value));
}
An idea?
I am trying to use jqxSchedular for my web app.
Schedular couldn't bind from remote data.
Here is my Angular component:
export class CourseScheduleComponent implements OnInit {
appointmentDataFields: any =
{
from: "start",
to: "end",
description: "description",
subject: "subject",
resourceId: "calendar"
};
source = {
dataType: "array",
dataFields: [
{ name: 'id', type: 'string' },
{ name: 'description', type: 'string' },
{ name: 'subject', type: 'string' },
{ name: 'calendar', type: 'string' },
{ name: 'start', type: 'date' },
{ name: 'end', type: 'date' }
],
localData: []
}
resources: any =
{
colorScheme: "scheme04",
dataField: "calendar",
source: new jqx.dataAdapter(this.source)
};
dataAdapter: any;
date: any = new jqx.date();
views: string[] | any[] =
[
'dayView',
'weekView',
'monthView',
'agendaView'
];
constructor(private repository: RepositoryService,private router: Router,
private activeRoute: ActivatedRoute ) { }
ngOnInit() {
this.getCourseSchedules().subscribe(res=>{
this.source.localData = res as CourseSchedule[];
},err=>{
console.log(err);
});
this.dataAdapter = new jqx.dataAdapter(this.source)
}
getCourseSchedules()
{
var courseId : string = this.activeRoute.snapshot.params['id'];
var apiUrl = `/api/course/schedule?courseId=${courseId}`;
return this.repository.getData(apiUrl).pipe(
map(data => {
let schedules = data as CourseSchedule[];
let newSchedules:CourseSchedule[] = [];
schedules.forEach((schedule) => {
const {start,end,...other} = schedule;
newSchedules.push(<CourseSchedule>{
start: new Date(start),
end: new Date(end),
...other
})
});
return newSchedules;
})
);
}
}
When I debug the ngOnInit there is no problem with setting localData. But when I consolled log source,it shows localdata is null.
I couldnt find for remote databinding example for Angular jqxSchedular.
So ,basicly it works with local data but at remote it doesnt work.
Please help about this.
You have to add them from the jqx component using addAppointment method as below:
getCourseSchedules()
{
let self = this;
var courseId : string = this.activeRoute.snapshot.params['id'];
var apiUrl = `/api/course/schedule?courseId=${courseId}`;
return this.repository.getData(apiUrl).pipe(
map(data => {
let schedules = data as CourseSchedule[];
let newSchedules:CourseSchedule[] = [];
schedules.forEach((schedule) => {
const {start,end,...other} = schedule;
var appointment = {
start: new Date(start),
end: new Date(end),
..other
};
self.myScheduler.addAppointment(appointment);
});
})
);
}
Please refer to the API for more details.
I want to call both a javascript function and a typescript function from the same event. It is a onClick event in a chart. I am relatively new to typescript and angular, so i dont know if what i am doing is even possible.
The problem is: I need to call a javascript function for getting a activated bar in the chart, and the typescript function to open a dialog in the angular component.
onClick: function(evt){
console.log(this);//<-- returns chart
bar: () => {console.log(this)}; //<-- here I try to get this as component
bar(); // <--doesnt work
//console.log(document.getElementById('myChart'));
}
Maybe bette if i show the whole thing.
public barChartOptions = {
scaleShowVerticalLines: false,
responsive: true,
events: ['mousemove', 'mouseout', 'click', 'touchstart', 'touchmove'],
onHover: console.log('onHover'),
onClick: function(evt){
//console.log(evt); Mouse Event
console.log(this);
const getFirst = array => console.log(this);
console.log(getFirst);
//bar: () => {console.log(this)};
//bar();
//console.log(document.getElementById('myChart'));
},
/*
onClick : (evt, datasets) => {
//let self = this;
//console.log(self);
if(datasets.length > 0){
this.openDialog();
console.log(this);
console.log(this.barChart);
}
},*/
scales: {
xAxes: [{
stacked: true
}],
yAxes: [{
stacked: true
}]
},
legend: {
display: true,
position: 'right'
},
tooltips: {
enabled: true,
mode: 'point'
}
};
this is my html template:
my-bar-dialog works!
<div>
<div style="display: block">
<canvas baseChart
id="myChart"
[datasets]="barChartData"
[labels]="barChartLabels"
[options]="barChartOptions"
[legend]="barChartLegend"
[chartType]="barChartType">
</canvas>
</div>
</div>
<button mat-raised-button (click)="openDialog()">Pick one</button>
<button (click)="openDialog()">Pick one</button>
Now, the thing is i have two different "this":
1)
onClick: function(evt){
let that = this;
let bar=()=> {console.log(that.this)};
bar();
},
2)
onClick : (evt, datasets) => {
if(datasets.length > 0){
console.log(this);
}
},
1 returns a char, 2 returns the component.
But i need both of them in the same Event/function as i need to call chartjs api functions and i need to call a function from my component.
And here my component
import { Component, OnInit, Inject } from '#angular/core';
import {MatDialog, MatDialogRef, MAT_DIALOG_DATA} from '#angular/material/dialog';
import { BarChartService } from '../bar-chart.service';
import { barChartClass } from '../barChartClass';
declare var foo: Function;
#Component({
selector: 'app-my-bar-dialog',
templateUrl: './my-bar-dialog.component.html',
styleUrls: ['./my-bar-dialog.component.css'],
})
export class MyBarDialogComponent implements OnInit {
client: string;
tenant: string;
constructor(public dialog: MatDialog, private barChartService: BarChartService) {
foo();
}
//First BarChart
barChart: barChartClass;
public barChartLabels: any;
public barChartType: any;
public barChartLegend: any;
public barChartData: any;
getBarChart(): void {
this.barChartService.getMockBarChart().subscribe(
barChart => this.barChart = barChart
);
this.barChartData = this.barChart.barChartData;
this.barChartLabels = this.barChart.barChartLabels;
this.barChartType = this.barChart.barChartType;
this.barChartLegend = this.barChart.barChartLegend;
}
public barChartOptions = {
scaleShowVerticalLines: false,
responsive: true,
events: ['mousemove', 'mouseout', 'click', 'touchstart', 'touchmove'],
onHover: console.log('onHover'),
onClick: function(evt){
//console.log(evt); Mouse Event
//console.log(this);
let that = this;
//bar: () => {console.log(this)};
let bar=()=> {console.log(that.this)};
bar();
//bar();
//console.log(document.getElementById('myChart'));
},
/*
onClick : (evt, datasets) => {
//let self = this;
//console.log(self);
if(datasets.length > 0){
this.openDialog();
console.log(this);
console.log(this.barChart);
}
},*/
scales: {
xAxes: [{
stacked: true
}],
yAxes: [{
stacked: true
}]
},
legend: {
display: true,
position: 'right'
},
tooltips: {
enabled: true,
mode: 'point'
}
};
openDialog(): void {
const dialogRef = this.dialog.open(DialogData, {
width: '250px',
data: {client: this.client, tenant: this.tenant}
});
dialogRef.afterClosed().subscribe(result => {
console.log('The dialog was closed');
this.client = result;
});
}
ngOnInit() {
this.getBarChart();
}
}
#Component({
selector: 'dialog-data',
templateUrl: 'dialog-data.html',
styleUrls: ['dialog-data.css']
})
export class DialogData {
constructor(
public dialogRef: MatDialogRef<DialogData>,
#Inject(MAT_DIALOG_DATA) public data: DialogData) {}
onNoClick(): void {
this.dialogRef.close();
}
}
What you're doing with the bar and the colon in the function is that you're trying to describe its type rather to declare it. So if you want to actually declare the function, do this:
onClick: function(evt) {
console.log(this);//<-- returns chart
let bar = () => { console.log(this) };
bar();
//console.log(document.getElementById('myChart'));
}
if you want to describe and declare it, do this:
onClick: function(evt) {
console.log(this);//<-- returns chart
let bar: () => void = () => { console.log(this) }; //<-- here I try to get this as component
bar(); // <--doesnt work
//console.log(document.getElementById('myChart'));
}
before using the chart in component assign this to some other variable like
var that=this
then in your chart
onClick: function(evt){
console.log(this);//<-- returns chart
let bar= () => {console.log(that)}; //<-- that should have your component refrence
}
Stackblitz demo
I'm fairly new to dat.GUI and I'm having problems getting it to work with a more complex variable.
I have the following:
let complexVariable= {
topLayer:
{
deeperLayer:
{
deepestLayer: 20,
//Other stuff
}
}
}
let gui = new dat.GUI();
gui.add(complexVariable, "topLayer.deeperLayer.deepestLayer", 10, 40);
This gives me the following error:
Uncaught Error: Object "[object Object]" has no property "topLayer.deeperLayer.deepestLayer"
Any help here would be appreciated.
It currently doesn't seem possible by looking at the source code. They use bracket notation with the single property you pass in on the object.
function add(gui, object, property, params) {
if (object[property] === undefined) {
throw new Error(`Object "${object}" has no property "${property}"`);
}
...
So what you are telling dat.GUI to do is find a top level property "topLayer.deeperLayer.deepestLayer" and that obviously does not exist on your object. It seems like more code would have to be written to support nested properties.
dat.gui would have to do something like if (object[property1][property2][...] === undefined) or in your case - complexVariable["topLayer"]["deeperLayer"]["deepestLayer"];
It's obvious that question is ~4 years old. But I was searching for the same and I found your question before realizing that it's possible. Below is E2E sample in Angular.
import { AfterViewInit, Component, ViewChild, ViewContainerRef } from '#angular/core';
import { GUI, GUIController, GUIParams } from 'dat.gui';
export type EditorMetadata = Array<IEditorFolder>;
export interface IDatState {
state: EditorMetadata;
instance: GUI;
metadata: EditorMetadata;
}
export interface IEditorFolder {
title: string;
property?: string;
tooltip: string;
elements?: Array<IEditorElement>;
folders?: Array<IEditorFolder>;
folderRef?: GUI;
}
export interface IEditorElement {
title: string;
tooltip: string;
options?: any;
elementRef?: GUIController;
target?: Object;
}
#Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.scss']
})
export class AppComponent implements AfterViewInit {
#ViewChild('container', { read: ViewContainerRef, static: true })
container: ViewContainerRef;
constructor() { }
ngAfterViewInit(): void {
this.composeEditor(this.container.element.nativeElement, options, foldersMetadata);
}
composeEditor(container: HTMLElement, editorOptions: GUIParams, editorMetadata: EditorMetadata): IDatState {
const
addFolder = (folder: IEditorFolder, parent: GUI): GUI => {
const
{ title, tooltip } = folder,
folderController = parent.addFolder(title);
folderController.domElement.setAttribute('title', tooltip);
return folderController;
},
addElement = (folder: GUI, element: IEditorElement, target: Object): GUIController => {
const
{ title, options, tooltip } = element,
elmController = folder
.add(target, title, options)
.name(title)
.onChange((value) => {
console.log(model);
});
elmController.domElement.setAttribute('title', tooltip);
return elmController;
},
createDat = (options: GUIParams, metadata: EditorMetadata): IDatState => {
const
state: IDatState = {
instance: new GUI(options),
state: JSON.parse(JSON.stringify(metadata)), // Don't touch original metadata, instead clone it.
metadata: metadata, // Return original metadata
};
return state;
},
process = (folders: EditorMetadata, parent: GUI, model: Object): void => {
folders.forEach(folder => {
const target: Object = folder.property ? model[folder.property] : model; // Root level or object nested prop?
folder.folderRef = addFolder(folder, parent);
folder.elements && folder.elements.forEach(element => element.elementRef = addElement(folder.folderRef, element, target));
folder.folders && process(folder.folders, folder.folderRef, target);
});
},
{ state, instance, metadata } = createDat(editorOptions, editorMetadata);
process(state, instance, model);
container.appendChild(instance.domElement);
return { state, instance, metadata };
}
}
const options: GUIParams = {
hideable: false,
autoPlace: false,
closeOnTop: false,
width: 250,
name: 'DAT Sample'
};
const model = {
rtl: true,
renderer: 'geras',
theme: 'dark',
toolbox: 'foundation',
toolboxPosition: 'left',
debug: {
alert: false
}
};
const foldersMetadata: EditorMetadata = [
{
title: 'Options',
tooltip: 'Options AA',
elements: [
{
title: 'rtl',
tooltip: 'RTL',
},
{
title: 'renderer',
tooltip: 'Renderer',
options: ['geras', 'thrasos', 'zelos']
},
{
title: 'theme',
tooltip: 'Theme',
options: ['classic', 'dark', 'deuteranopia', 'tritanopia', 'highcontrast']
},
{
title: 'toolbox',
tooltip: 'Toolbox',
options: ['foundation', 'platform', 'invoice']
},
{
title: 'toolboxPosition',
tooltip: 'Toolbox Position',
options: ['left', 'right', 'top', 'bottom']
},
],
folders: [
{
title: 'Debug',
property: 'debug',
tooltip: 'Debug mode',
elements: [
{
title: 'alert',
tooltip: 'Alert Tooltip',
},
]
}
]
},
];
i want to bind the json file to a smart table. How to use the loop function for the iteration.. please help
It only shows the design of smart table.
didn't binding the data from json
this is the json file
[
{
"year": 2013,
"id": "",
"doctor": "Dr. Smith",
"illness": "Flu",
"apptdate": "3/12/2013",
"details":"Patient had flu for 5 days. No medicines prescribed"
}
]
i used to retrieve data using
#Injectable()
export class SmartTablesService {
constructor(private http: Http) {
}
smartTableData = [];
loadData() {
console.log('loadData');
this.http.get('http://192.168.0.100:8000/medical')
.subscribe((data) => {
setTimeout(() => {
var contactData = [];
$.each(data.json(), function (key, value) {
var tempData = value.source;
contactData.push(tempData);
});
this.smartTableData = contactData;
}, 1000);
});
}
getData(): Promise<any> {
console.log("Promise");
this.loadData();
return new Promise((resolve, reject) => {
setTimeout(() => {
console.log(this.smartTableData);
resolve(this.smartTableData);
}, 3000);
});
}
}
constructor(private http: Http) { }
getComments() {
return this.http.get('http://192.168.0.100:8000/article' )
.map((res: Response) => res.json())
.catch((error:any) => Observable.throw(error));
}
}*/
this is the component part
#Component({
selector: 'new',
template: '<ng2-smart-table [settings]="settings" [source]="source"></ng2-smart-table>'
})
export class NewComponent {
query: string = '';
settings = {
noDataMessage: 'Loading...',
columns: {
year: {
title: 'YEAR',
type: 'string'
},
id: {
title: 'ID',
type: 'string'
},
doctor: {
title: 'DOCTOR',
type: 'string'
},
illness: {
title: 'ILLNESS',
type: 'string'
},
apptdate: {
title: 'APPTDATE',
type: 'string'
},
details: {
title: 'DETAILS',
type: 'string'
}
}
};
// data
source: LocalDataSource = new LocalDataSource();
constructor(protected service: SmartTablesService){
this.service.getData().then((data) => {
this.source.load(data);
});
}
}
please anyone anyone know how to bind it ..help
simply change the subscribe part in the service page to
var tempData = value;
so .subscriber looks like
.subscribe((data) => {
setTimeout(() => {
var contactData = [];
$.each(data.json(), function (key, value) {
var tempData = value; contactData.push(tempData);
});
this.smartTableData = contactData;
}, 1000);
});
}
it works..!