Printing Custom Object in ionic 2 - ionic2

There is a class in my app SL-Leg.It has some variables which would hold the values.
When i print object of this class then [object object] is being printed
but when i try to access the value of the class by myObject.line for example then there is an error undefined is not an object (evaluating self.context.$implicit.line
leglist is array which holds the objects from class SL'Leg.
<ion-header>
<ion-navbar>
<ion-title>showTripInfo</ion-title>
</ion-navbar>
</ion-header>
<ion-content padding>
<ion-content class="show-trips">
<ion-list>
<ion-item-group *ngFor="let leg of legList" (click) = "showTripInfo(tp)">
<ion-card>
<table style="width:100%">
<tr>
<div class="page-show-trips.card-title">
<th item-width="100%">{{leg}} >> {{leg.line}}</th>
</div>
</tr>
<tr>
<div class="page-show-trips.card-subtitle">
<th item-width="100%">{{leg}} >> {{leg}}</th>
</div>
</tr>
</table>
<div ng-repeat="(key, value) in tp.LegList" > {{key}} {{value}} </div>
</ion-card>
</ion-item-group>
</ion-list>
</ion-content>
</ion-content>
SL-Leg is here
i
mport { Component } from '#angular/core';
import { NavController, NavParams } from 'ionic-angular';
import { Address } from './sl-Address';
/*
Generated class for the SlTripClass page.
See http://ionicframework.com/docs/v2/components/#navigation for more info on
Ionic pages and navigation.
*/
#Component({
selector: 'page-sl-legs',
//templateUrl: 'sl-trip-class.html'
})
export class Leg {
// public from_time: String;
public legIndex: Number;
public enabled_TransportType: Boolean; // Default True
public enabled_LineNumber: Boolean; // Default true
public showHideLeg: Boolean; // Default true means show all legs
public filterLine: Boolean;
public filterDepartures: Boolean;
// ...:Common publiciables available in Travel /Walk
public journeyType : String;
// available via LegDetail
public origin: Address;
public destination: Address;
public name: String;
public type: String;
public idx: String;
public geomRef: String;
public legImageName: String;
//-- Only found in --------Walk
public dist: String;
public hide: String;
//-- Only found in --------Travel
public dir: String;
public line: String;
public journeyDetailRef: String;
public rtu_Message_Flag: Boolean;
public rtu_Message: String;
// constructor(public tripObjectFromSl: any,public navCtrl: NavController, public navParams: NavParams) {
constructor() {
this.legIndex = 0;
this.enabled_TransportType= true; // Default True
this.enabled_LineNumber= true;
this.showHideLeg= true;
this.filterLine= false;
this.filterDepartures;
this.journeyType= String();;
this.origin= new Address();
this.destination= new Address();
this.name= String();
this.type= String();
this.idx= String();
this.geomRef= String();
this.legImageName= String();
this.dist= String();
this.hide= String();
//-- Only found in --------Travel
this.dir= String();
this.line= String();
this.journeyDetailRef= String();
this.rtu_Message_Flag= true;
this.rtu_Message= String();
}
ionViewDidLoad() {
console.log('ionViewDidLoad SlTripClassPage');
}
}

The first object in the array LegList is null or undefined.
You could just put a null check
{{leg?.line}}
Also the legIndex value starts from 1.
I suppose you are inserting with for loop starting index 1.

Related

Angular 6 production build error with buildOptimizer and aot

My Angular 6 project will not build with the command;
ng build --prod --configuration=production --base-href=/quickorder/
and gives the errors;
ERROR in src\app\order-input\order-input.component.html(43,17): : Property 'number' does not exist on type 'OrderInputComponent'.
src\app\order-input\order-input.component.html(58,57): : Property 'autoCorrect' does not exist on type 'OrderInputComponent'.
src\app\order-input\order-input.component.html(58,19): : Property 'value' does not exist on type 'OrderInputComponent'.
src\app\order-input\order-input.component.html(72,19): : Property 'value' does not exist on type 'OrderInputComponent'.
src\app\order-input\order-input.component.html(82,19): : Property 'value' does not exist on type 'OrderInputComponent'.
src\app\order-input\order-input.component.html(112,31): : Property 'checked' does not exist on type 'OrderInputComponent'.
src\app\order-input\order-input.component.html(112,31): : Property 'checked' does not exist on type 'OrderInputComponent'.
These seem to be coming from my kendo-ui components.
My angular.json;
"configurations": {
"production": {
"fileReplacements": [
{
"replace": "src/environments/environment.ts",
"with": "src/environments/environment.prod.ts"
}
],
"optimization": true,
"outputHashing": "all",
"sourceMap": false,
"extractCss": true,
"namedChunks": false,
"aot": true,
"extractLicenses": true,
"vendorChunk": false,
"buildOptimizer": true
}
}
},
However, if I set aot and buildOptimizer to false, it works. Is this a problem with Angular or am I doing something wrong?
Some of the html;
<label class="k-form-field required" for="product" style="width: 40%; display: inline-block">
<span>Select Product</span>
<kendo-autocomplete class="form-control" id="product" name="product" required validationMessage="Select Product"
[popupSettings]="{width: 400}"
style="width: 100%;"
[data]="listItems"
**Line 43-->[value]=number**
[valueField]="'PackDescription'"
[filterable]="true"
[placeholder]="'e.g. Wheat or 25KG (3 character minimum)'"
(valueChange)="valueChange($event)"
(filterChange)="filterChange($event)"
[(ngModel)]="product"
[ngModelOptions]="{standalone: true}">
</kendo-autocomplete><span class="k-invalid-msg" data-for="product"></span>
</label>
<label class="k-form-field required" for="quantities" style="display: inline-block">
<span>Quantity</span>
<!-- <input style="width: 150px" type="number" class="form-control" [(ngModel)]="quantity" name="quantities" id="quantities" required validationMessage="Select Quantity"> -->
<kendo-numerictextbox
[value]="value" [min]="1" [max]="200" [autoCorrect]="autoCorrect"
[(ngModel)]="quantity"
[ngModelOptions]="{standalone: true}">
</kendo-numerictextbox>
<span class="k-invalid-msg" data-for="quantities"></span>
</label>
Thr .ts;
export class OrderInputComponent implements OnInit {
MINFILTERLENGTH: number = 3;
ref: string;
name: string;
repRef: string;
allData: any[];
xrefAddress = [];
addressListItems: Array<Object> = [];
listItems: Array<Object> = [];
selectedItem: Object;
orderLines: Array<Object> = [];
total: number;
addressNumber: string;
productNumber: string;
defaultAddressItem: { name: string, number: number } = {name: "Select Address...", number: null};
newOrderLines: Array<Object> = [];
tradingpartner: string;
product: string;
productRef: string;
productDesc: string;
quantity: number;
price: number;
selectedValue: number;
orderRef: string = null;
orderError: string = null;
fd: Date;
td: Date;
fromDate: string;
toDate: string;
collection: boolean;
debug: boolean = false;
comments: string;
public events: string[] = [];
constructor( private user: UserService,
private router:Router,
private orders: OrdersService,
private route: ActivatedRoute,
private productXref: ProductXrefService,
private addressXref: AddressXrefService,
private intl: IntlService,
private createOrderService: CreateOrderService,
private globalsService: GlobalsService,
private location: Location,
private ngxXml2jsonService: NgxXml2jsonService,
private localStorageService: LocalStorageService) {
Thanks in advance for any help,
Mark.
P.S. I should add that ng serve and ng build work fine.
I don't know why, but sometimes with the kendo controls, adding or removing the [] will get you through this error:
autoCorrect="autoCorrect" instead of [autoCorrect]="autoCorrect"
Hope this helps!

JSON object exists but when a property is selected return undefined on ionic 2

I've a very problem with ionic 2, I'm obtaining a JSON object and I can check that object data exists using the code <span>{{ user|json }}</span>, but when I'm using the the code <span>{{ user.id }}</span> an exception is displayed with the message "can not read property id of null". The this.userService.get( this.user_id ) method is used on another section and this working fine, but in this section not, can you help me with it?
This is my code:
<!-- my profile.html view -->
<ion-row>
<ion-col col-4>
Tipo de socio
</ion-col>
<ion-col col-8>
<span>{{ user.id }}</span><!-- cannot read id property of a null -->
</ion-col>
</ion-row>
<ion-row>
<ion-col col-4>
Tipo de socio
</ion-col>
<ion-col col-8>
<span>{{ user|json }}</span><!-- the data is returned -->
</ion-col>
</ion-row>
// My profile.ts ( where I'm loading the view and calling the user services )
import { User, UserService } from '../../app/models/user';
#Component({
selector: 'page-profile',
templateUrl: 'profile.html'
})
export class ProfilePage {
title = 'My Profile';
user: User = null;
private user_id: number = 0;
constructor(
public navCtrl: NavController,
public navParams: NavParams,
public alertCtrl: AlertController,
public modalCtrl: ModalController,
public loadingCtrl: LoadingController,
public userService: UserService) {
this.user_id = this.navParams.get('user_id'); // this value is working fine!
if ( this.user_id > 0 ) {
this.userService.get( this.user_id ).then( user => this.user = user );
}
}
ionViewDidLoad() { }
}
// My user.ts ( where I've my services )
#Injectable()
export class User {
id: number;
name: string;
email: string;
ic: number;
birth_date: string;
home_phone: number;
phone: number;
is_active: boolean;
is_admin: boolean;
from_social_account: boolean;
is_superuser: boolean;
status: boolean;
created_at: any;
updated_at: any;
groups: any;
permissions: any;
addresses: any;
all_permissions: any;
auth_token: string;
is_customer: boolean;
is_partner: boolean;
last_login: string;
profile: any;
requests: any;
skills: any;
social_providers: any;
wallets: any;
errors: any = null;
birth_date_no_formatted: string;
main_address: any;
}
#Injectable()
export class UserService {
private headers: Headers = new Headers(Constant.DEFAULT_HEADERS);
private url: string = `${Constant.API_HOST}${Constant.API_PREFIX}${Constant.API_V1}`;
constructor(
private http: Http) { }
get( _id: number ): Promise<User> {
let url = `${this.url}users/${_id}/`;
return this.http.get(url, { headers: this.headers })
.toPromise().then( response => response.json() as User ).catch(this.handleError);
}
private handleError(error: any): any {
console.log( JSON.stringify( error ) );
return {errors: StaticMethods.formatSubmitErrors( error.json() ) };
}
}
Your code actually works but try to show null value until return promise data.
To fix problem, you can use safe-navigation operator like this :
{{ user?.id }}
So, id and others is only read when user not null.

How add my geolocation as origin in angular2

the code is found ok, only need help to add my geolocation as origin, some one can helpme ?the base of my code
this is my component.ts or my contact.ts from ionic2
import { Component, NgModule,NgZone,OnInit,ViewChild,ElementRef,Directive,Input } from '#angular/core';
import {FormControl, FormsModule, ReactiveFormsModule}from'#angular/forms';
import {BrowserModule} from '#angular/platform-browser';
import { Geolocation} from '#ionic-native/geolocation';
import { DirectionsMapDirective} from '../../mapD/DirectionsMap.directive';
import {AgmCoreModule,MapsAPILoader, GoogleMapsAPIWrapper} from '#agm/core';
import {} from '#types/googlemaps';
declare var google: any;
declare var jQuery: any;
#Component({
selector: 'page-contact',
templateUrl: 'contact.html',
providers:[GoogleMapsAPIWrapper]
})
export class ContactPage implements OnInit{
public latitude: number;
public longitude: number;
public destinationInput: FormControl;
public destinationOutput: FormControl;
public zoom: number;
public iconurl: string;
public mapCustomStyles : any;
public estimatedTime: any;
public estimatedDistance: any;
#ViewChild("pickupInput")
public pickupInputElementRef: ElementRef;
#ViewChild("pickupOutput")
public pickupOutputElementRef: ElementRef;
#ViewChild("scrollMe")
private scrollContainer: ElementRef;
#ViewChild(DirectionsMapDirective) vc: DirectionsMapDirective;
public origin :any ; // its a example aleatory position
public destination : any; // its a example aleatory position
constructor(
private mapsAPILoader: MapsAPILoader,
private ngZone: NgZone,
private gmapsApi: GoogleMapsAPIWrapper,
private _elementRef : ElementRef
) {
}
ngOnInit() {
//set google maps defaults
this.zoom = 4;
this.latitude = 39.8282;
this.longitude = -98.5795;
//this.iconurl = '../image/map-icon.png';
this.iconurl = '../image/map-icon.png';
// this.mapCustomStyles = this.getMapCusotmStyles();
//create search FormControl
this.destinationInput = new FormControl();
this.destinationOutput = new FormControl();
console.log(this.destinationInput)
console.log(this.destinationOutput)
//set current position
this.setCurrentPosition();
//load Places Autocomplete
this.mapsAPILoader.load().then(() => {
let autocompleteInput = new google.maps.places.Autocomplete(this.pickupInputElementRef.nativeElement, {
types: ["address"]
});
let autocompleteOutput = new google.maps.places.Autocomplete(this.pickupOutputElementRef.nativeElement, {
types: ["address"]
});
this.setupPlaceChangedListener(autocompleteInput, 'ORG');
this.setupPlaceChangedListener(autocompleteOutput, 'DES');
});
}
private setupPlaceChangedListener(autocomplete: any, mode: any ) {
autocomplete.addListener("place_changed", () => {
this.ngZone.run(() => {
//get the place result
let place: google.maps.places.PlaceResult = autocomplete.getPlace();
//verify result
if (place.geometry === undefined) {
return;
}
if (mode === 'ORG') {
this.vc.origin = { longitude: place.geometry.location.lng(), latitude: place.geometry.location.lat() };
this.vc.originPlaceId = place.place_id;
} else {
this.vc.destination = { longitude: place.geometry.location.lng(), latitude: place.geometry.location.lat() }; // its a example aleatory position
this.vc.destinationPlaceId = place.place_id;
}
if(this.vc.directionsDisplay === undefined){ this.mapsAPILoader.load().then(() => {
this.vc.directionsDisplay = new google.maps.DirectionsRenderer;
});
}
console.log(this.vc.originPlaceId);
//Update the directions
this.vc.updateDirections();
this.zoom = 12;
});
});
}
getDistanceAndDuration(){
this.estimatedTime = this.vc.estimatedTime;
this.estimatedDistance = this.vc.estimatedDistance;
}
scrollToBottom(): void {
jQuery('html, body').animate({ scrollTop: jQuery(document).height() }, 3000);
}
private setPickUpLocation( place:any ) {
//verify result
if (place.geometry === undefined || place.geometry === null) {
return;
}
//set latitude, longitude and zoom
this.latitude = place.geometry.location.lat();
this.longitude = place.geometry.location.lng();
this.zoom = 40;
}
private setCurrentPosition() {
if ("geolocation" in navigator) {
navigator.geolocation.getCurrentPosition((position) => {
this.latitude = position.coords.latitude;
this.longitude = position.coords.longitude;
this.zoom = 12;
});
}
}
private getMapCusotmStyles() {
// Write your Google Map Custom Style Code Here.
}
}
this is the directive in ionic 2
import { Directive, Input, Output } from '#angular/core';
import { GoogleMapsAPIWrapper} from'#agm/core';
declare var google: any;
#Directive({selector:'agm-map-directions'})
export class DirectionsMapDirective{
#Input() origin:any ;
#Input() destination:any;
#Input() originPlaceId:any;
#Input() destinationPlaceId:any;
#Input() waypoints:any;
#Input() directionsDisplay:any;
#Input() estimatedTime : any;
#Input() estimatedDistance : any;
constructor (private gmapsApi: GoogleMapsAPIWrapper) {}
updateDirections(){
this.gmapsApi.getNativeMap().then(map => {
if(!this.originPlaceId || !this.destinationPlaceId
){
return;
}
console.log(this.originPlaceId);
var directionsService = new google.maps.DirectionsService;
var me = this;
var latLngA = new google.maps.LatLng({lat: this.origin.latitude, lng: this.origin.longitude });
var latLngB = new google.maps.LatLng({lat: this.destination.latitude, lng: this.destination.longitude });
this.directionsDisplay.setMap(map);
this.directionsDisplay.setOptions({
polylineOptions: {
strokeWeight: 8,
strokeOpacity: 0.7,
strokeColor: '#00468c'
}
});
this.directionsDisplay.setDirections({routes: []});
directionsService.route({
origin: {placeId : this.originPlaceId },
destination: {placeId : this.destinationPlaceId },
avoidHighways: true,
travelMode: google.maps.DirectionsTravelMode.DRIVING
//travelMode: 'DRIVING'
}, function(response: any, status: any) {
if (status === 'OK') {
me.directionsDisplay.setDirections(response);
map.setZoom(30);
//console.log(me.getcomputeDistance (latLngA, latLngB));
var point = response.routes[ 0 ].legs[ 0 ];
me.estimatedTime = point.duration.text ;
me.estimatedDistance = point.distance.text;
console.log(me.estimatedTime);
console.log( 'Estimated travel time: ' + point.duration.text + ' (' + point.distance.text + ')' );
} else {
console.log('Directions request failed due to ' + status);
}
});
});
}
private getcomputeDistance(latLngA: any , latLngB: any )
{
return (google.maps.geometry.spherical.computeDistanceBetween(latLngA, latLngB) / 1000).toFixed(2);
}
}
this is html
<ion-header>
<ion-navbar>
<ion-title>
mapa
</ion-title>
</ion-navbar>
</ion-header>
<ion-content>
<agm-map [latitude]="lat" [longitude]="lng" [scrollwheel]="false"
[zoom]="zoom" [styles]="mapCustomStyles">
<agm-marker [latitude]="lat" [longitude]="lng" [iconUrl]="iconurl">
<agm-info-window>
<strong>InfoWindow content</strong>
</agm-info-window>
</agm-marker>
<agm-map-directions [origin]="origin" [destination]="destination"></agm-map-directions>
</agm-map>
<br>
<br>
<br>
<br>
<br>
<div class="form-group">
<input placeholder="Enter source location" autocorrect="off" autocapitalize="off" spellcheck="off"
type="text" class="form-control" #pickupInput [formControl]="destinationInput">
<input placeholder="Enter destination" autocorrect="off" autocapitalize="off" spellcheck="off"
type="text" class="form-control" #pickupOutput [formControl]="destinationOutput">
</div>
</ion-content>
my code is from http://www.17educations.com/angularjs-2/google-map-directions-display-angular-2/

map is not a function

I am trying to make an website that connets with a weather api and gets some info about current weather in given city. When i looked at network flow in my application i do recive a json that contais that information but i cannot map it and display results. Error i revice is :
TypeError: response.json(...).map is not a function WeatherSearchComponent.ts:138
at MapSubscriber.project (WeatherSearchComponent.ts:84)
at MapSubscriber._next (map.js:77)
at MapSubscriber.Subscriber.next (Subscriber.js:89)
at XMLHttpRequest.onLoad (http.umd.js:1083)
at ZoneDelegate.invokeTask (zone.js:225)
at Object.onInvokeTask (core.umd.js:6004)
at ZoneDelegate.invokeTask (zone.js:224)
at Zone.runTask (zone.js:125)
at XMLHttpRequest.ZoneTask.invoke (zone.js:293)
Heres WeatherSearchComponent:
import {
Component,
Injectable,
OnInit,
ElementRef,
EventEmitter,
Inject
} from '#angular/core';
import { Http, Response } from '#angular/http';
import { Observable } from 'rxjs';
import 'rxjs/Rx';
import 'rxjs/add/operator/map';
export var WEATHER_API_KEY: string = 'api_key';
export var WEATHER_API_URL: string ='http://api.openweathermap.org/data/2.5/weather';
export var GDANSK_ID: string = '3099434';
/*let loadingGif: string = ((<any>window).__karma__) ? '' :
require('images/loading.gif');*/
class SearchResult {
content: string;
constructor(obj?: any) {
this.content= obj && obj.content ||
WEATHER_API_URL + 'id=' + obj.city + 'appid=' + WEATHER_API_KEY;
}
}
// http://api.openweathermap.org/data/2.5/weather?
// id=3099434&appid=api_key
#Injectable()
export class WeatherService {
constructor(private http: Http,
#Inject(WEATHER_API_KEY) private apiKey: string,
#Inject(WEATHER_API_URL) private apiUrl: string) {
}
search(city: string): Observable<SearchResult[]> {
let params: string = [
`q=${city}`,
`appid=${this.apiKey}`
].join('&');
let queryUrl: string = `${this.apiUrl}?${params}`;
console.log("query url" , queryUrl);
var getRequest = this.http.get(queryUrl);
console.log("getRequest", getRequest);
return getRequest
.map((response: Response) => {
return (<any>response.json()).map(item => {
console.log("raw item", item); // uncomment if you want to debug
return new SearchResult({
content: item.main.temp
});
});
});
}
}
export var weatherServiceInjectables: Array<any> = [
{provide: WeatherService, useClass: WeatherService},
{provide: WEATHER_API_KEY, useValue: WEATHER_API_KEY},
{provide: WEATHER_API_URL, useValue: WEATHER_API_URL}
];
/**
* SearchBox displays the search box and emits events based on the results
*/
#Component({
outputs: ['loading', 'results'],
selector: 'search-box',
template: `
<input type="text" class="form-control" placeholder="Search" autofocus>
`
})
export class SearchBox implements OnInit {
loading: EventEmitter<boolean> = new EventEmitter<boolean>();
results: EventEmitter<SearchResult[]> = new EventEmitter<SearchResult[]> ();
constructor(private weather: WeatherService,
private el: ElementRef) {
}
ngOnInit(): void {
// convert the `keyup` event into an observable stream
var observable =
Observable.fromEvent(this.el.nativeElement, 'keyup');
observable
.map((e: any) => e.target.value) // extract the value of the input
.filter((text: string) => text.length > 1) // filter out if empty
.debounceTime(250) // only once every 250ms
.do(() => this.loading.next(true)) // enable loading
// search, discarding old events if new input comes in
.map((query: string) => this.weather.search(query))
.switch()
// act on the return of the search
.subscribe(
(results: SearchResult[]) => { // on sucesss
this.loading.next(false);
this.results.next(results);
},
(err: any) => { // on error
console.log(err);
this.loading.next(false);
},
() => { // on completion
this.loading.next(false);
}
);
}
}
#Component({
inputs: ['result'],
selector: 'search-result',
template: `
<div class="col-sm-6 col-md-3">
<div class="thumbnail">
<img src="{{result.thumbnailUrl}}">
<div class="caption">
<h3>{{result}}</h3>
<p>{{result}}</p>
<p><a href="{{result.videoUrl}}"
class="btn btn-default" role="button">Watch</a></p>
</div>
</div>
</div>
`
})
export class SearchResultComponent {
result: SearchResult;
}
#Component({
selector: 'weather-search',
template: `
<div class='container'>
<div class="page-header">
<h1>Weather Search</h1>
</div>
<div class="row">
<div class="input-group input-group-lg col-md-12">
<search-box
(loading)="loading = $event"
(results)="updateResults($event)"
></search-box>
</div>
</div>
<div class="row">
<search-result
*ngFor="let result of results"
[result]="result">
</search-result>
</div>
</div>
`
})
export class WeatherSearchComponent {
results: SearchResult[];
updateResults(results: SearchResult[]): void {
this.results = results;
// console.log("results:", this.results); // uncomment to take a look
}
}
This is what i do recive from api call :
/*
{"coord":{"lon":18.65,"lat":54.35},
"weather":[{"id":801,"main":"Clouds",
"description":"few clouds","icon":"02n"}],"base":"stations",
"main":{"temp":270.15,"pressure":1035,"humidity":92,
"temp_min":270.15,"temp_max":270.15},"visibility":10000,
"wind":{"speed":2.1,"deg":290},"clouds":{"all":20},
"dt":1484665200,
"sys":{"type":1,"id":5349,"message":0.0029,
"country":"PL","sunrise":1484636080,"sunset":1484665040},"
id":3099434,"name":"Gdansk","cod":200}
*/
It's not clear from your question whether you're trying to .map() on a variable or on an observable.
Scenario #1: variable.map()
variable must be an array. Looks from your code that your variable contains an object.
const jsonData = {
"coord":{"lon":18.65,"lat":54.35},
// Abridged for brevity...
id":3099434,"name":"Gdansk","cod":200
};
jsonData.map(...); // WON'T WORK - `jsonData` must be an array
Scenario #2: observable.map()
You must import the map operator in your code before mapping:
import 'rxjs/add/operator/map';
// Then, later
Observable.map(...);

Ionic2 DateTime not displayed

I am trying to make use of the Ionic DateTime component. I have the following code, but nothing displays (just the label and button). If anyone can advise, I would appreciate it.
datetime.html
<ion-header>
<ion-navbar>
<ion-title>Last Online</ion-title>
</ion-navbar>
</ion-header>
<ion-content padding>
<center>
<ion-spinner icon="android" *ngIf="loading"></ion-spinner>
</center>
<ion-row>
<ion-col>
<center>
<ion-label>Last Online</ion-label>
<ion-datetime displayFormat="h:mm A" pickerFormat="h mm A" [(ngModel)]="event.timeStarts"></ion-datetime>
</center>
</ion-col>
</ion-row>
<ion-buttons>
<button (click)="done()" block round class="form-button-text">{{'Done'}}</button>
</ion-buttons>
</ion-content>
datetime.ts
import { Component } from '#angular/core';
import { NavController, NavParams, Events } from 'ionic-angular';
import { JobModel } from '../model/jobModel';
#Component({
templateUrl: 'build/pages/datetime/datetime.html'
})
export class DateTimePage {
private loading: boolean = true;
private jobModel: JobModel = null;
private event: Events = null;
constructor(private nav: NavController, private navParams: NavParams, event: Events) {
this.event = event;
this.jobModel = navParams.get('jobModel');
if (!this.jobModel) {
this.jobModel = new JobModel();
}
this.loading = false;
}
private done(): void {
alert('todo');
}
}
The following works, it's a different date picker.
http://ionicframework.com/docs/v2/components/#datetime