Remove Element On Click: Ionic 2

This is a basic example wherein we have a list of company names and once the user clicks on individual name, that name gets removed from the list. We’ve not included the http calls and database in this example to keep things simple and minimalistic.

Related Read:
Basics of Page Component: Ionic 2
ngIf, index, first, last: Ionic 2

Remove Element On Click: Ionic 2


[youtube https://www.youtube.com/watch?v=ZkHQXqFa0I0]

YouTube Link: https://www.youtube.com/watch?v=ZkHQXqFa0I0 [Watch the Video In Full Screen.]



src/pages/home/home.ts

import { Component } from '@angular/core';
import { NavController } from 'ionic-angular';
 
@Component({
  selector: 'page-home',
  templateUrl: 'home.html'
})
export class HomePage {
companies: Array< {}>;
  constructor(public navCtrl: NavController) {
    this.companies = [
      {name: 'Microsoft', code: 1},
      {name: 'Apple', code: 2},
      {name: 'Google', code: 3},
      {name: 'Oracle', code: 4},
      {name: 'IBM', code: 5}
    ];
  }
  remove(no){
    (this.companies).splice(no, 1);
  };
}

Here we have an array variable called companies, which has 5 company names in object format. We also have a method called remove which takes 1 parameter. This parameter is the index number of the item being clicked by the user. Once we get this index number we make use of JavaScript’s splice() method and remove the element from the array. Splice takes 2 arguments, the first one being the index(or the position) of the element to be removed and the second argument is the number of elements to be removed from position of the index received.

src/pages/home/home.html

< ion-list no-lines>
  < ion-item *ngFor="let company of companies; 
                     let i = index;" 
             (click)="remove(i);">
     {{company.name}}
  < /ion-item>
< /ion-list>

Here we assign index value to a variable i. We then pass this value of i to remove method once the user clicks on an item. i.e., we pass the index value of the item being clicked by the user, to the remove method.

Real-time Applications
In real-time applications we’ll pass a unique id of the clicked element to the remove method, which is then passed on to some http calls, which removes the item from the database(usually) and if the remove operation is successful we’ll remove the item from the User Interface using JavaScripts Splice() method. And if the remove operation fails, we’ll display appropriate message to the user.

Positioning The Tabs: IONIC APPS

Some components like tabs, titles behave according to the platform they are built for. For example, on iOS the default display of tabs is at the bottom and at top in android devices.


ionic-tabs-position

This might look like a minor thing at the beginning of app development, but when we want to place an ad or social sharing icons at the bottom, we might like to place the tabs at the top or visa-versa!

To have consistent looks across platforms we can ‘hard set’ the tabs location by setting the tabs.position function of $ionicConfigProvider.

$ionicConfigProvider.tabs.position() takes 2 values:
1. top
2. bottom


[youtube https://www.youtube.com/watch?v=tXW7Px7A3qo]

YouTube Link: https://www.youtube.com/watch?v=tXW7Px7A3qo [Watch the Video In Full Screen.]



To center the title of header you can make use of following syntax:

< ion-header-bar
  title="headerTitle"
  left-buttons="leftButtons"
  right-buttons="rightButtons"
  type="bar-positive"
  align-title="center">
< /ion-header-bar>

Google Maps Integration: HTML5

In this video tutorial we illustrate the implementation of Google Maps API.

Here we supply latitude and longitude values fetched by Geolocation API and feed it to Google Map API, which is turn returns the location on its MAP.

globe-latitude-longitude

It has 4 variations:
ROADMAP (normal, default 2D map)
SATELLITE (photographic map)
HYBRID (photographic map + roads and city names)
TERRAIN (map with mountains, rivers, etc.)

HTML File
index.html

1
2
3
4
5
6
7
8
9
10
11
12
13
14
< !doctype html>
<html>
 <head>
  <title>Geolocation API: Technotip.com</title>
  <meta charset="utf-8"/>
  <link href="css/myStyle.css" rel="stylesheet"/>
  <script src="js/jquery-1.10.1.min.js"></script>
  <script src="http://maps.google.com/maps/api/js?sensor=true"></script>
  <script src="js/myScript.js"></script>
 </head>
 <body>
  <p id="map"></p>
 </body>
</html>

Here we’ve added an id to paragraph tag. And included Google Map API’s javascript file within the head tag. We must include it before myScript.js, as we’ll be using Google Map API’s inside myScript.js

Javascript File: Google Map API
myScript.js

1
2
3
4
5
6
7
8
9
10
11
12
13
14
function success(position)
{
var googleLatLng = new google.maps.LatLng(position.coords.latitude, 
  position.coords.longitude);
var mapOtn={
zoom:10,
center   : googleLatLng,
mapTypeId: google.maps.MapTypeId.ROAD
}
 
var Pmap= document.getElementById("map");
 
var map= new google.maps.Map(Pmap, mapOtn);
}

Pass position.coords.latitude and position.coords.longitude values to LatLng constructor of Google Maps API, which converts it into googleLatLng object.

Set the options of Google Maps:
zoom takes value from 0 to 21.
We center the map to our users/visitors location.
map type: ROADMAP, SATELLITE, HYBRID, TERRAIN.

Full Javascript File: Google Map API
myScript.js

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
$(document).ready(function(){
 
if( navigator.geolocation )
 navigator.geolocation.getCurrentPosition(success, fail);
else
 $("p").html("HTML5 Not Supported");
 
});
 
function success(position)
{
var googleLatLng = new google.maps.LatLng(position.coords.latitude, 
  position.coords.longitude);
var mapOtn= {
zoom:10,
center   :googleLatLng,
mapTypeId:google.maps.MapTypeId.ROAD
}
 
var Pmap= document.getElementById("map");
 
var map= new google.maps.Map(Pmap, mapOtn);
}
 
function fail(error)
{
var errorType = {
0: "Unknown Error",
1: "Permission denied by the user",
2: "Position of the user not available",
3: "Request timed out"
};
 
var errMsg = errorType[error.code];
 
if(error.code == 0 || error.code == 2){
errMsg = errMsg+" - "+error.message;
}
 
$("p").html(errMsg);
}

For explanation of other parts of above code:
Geolocation API – Success Handler: HTML5
Geolocation API – Error Handle: HTML5

Google Maps API Integration: HTML5


[youtube https://www.youtube.com/watch?v=UroKHzuuve8]

YouTube Link: https://www.youtube.com/watch?v=UroKHzuuve8 [Watch the Video In Full Screen.]



Note:
If you’re accessing this application via your desktop computer, then it may be showing you the location of your ISP’s(Internet Service Provider’s) local office location.
To get the accurate location, access our demo page via your smart phone.

Google Maps: Demo

Smartphone
1. Install Google Chrome browser.
2. Switch on your GPS and permit Google to access your location information, for testing purpose.
3. Visit our demo link(present above).
4. Move around and see your location information being updated in real-time.
5. We’ll teach you to make your application show real time data in coming videos, stay subscribed :-)

Geolocation API – Success Handler: HTML5

In this video tutorial we’ll show you how to write your first(simple) HTML5 geolocation API application. Basics of Geolocation API is also explained in the notes below, so don’t skip, read and practice it.

Technologies included
Basic HTML5 tags
jQuery – for Javascript
CSS basics

With Geolocation API we can know our position/location on earth by fetching the latitude and longitude information from the browser.

HTML5 File
index.html

1
2
3
4
5
6
7
8
9
10
11
12
13
< !doctype html>
<html>
 <head>
  <title>Geolocation API: Technotip.com</title>
  <meta charset="utf-8"/>
  <link href="css/myStyle.css" rel="stylesheet"/>
  <script src="js/jquery-1.10.1.min.js"></script>
  <script src="js/myScript.js"></script>
 </head>
 <body>
  <p></p>
 </body>
</html>

Here we’re making use of HTML5 markup.
Know more: HTML5 – Getting Started Guide

We’re also including a jQuery library file. Make sure to include it before our custom javascript file(myScript.js), as our javascript file depends on jQuery library file.

CSS File
myStyle.css

1
2
3
4
p{
width: 300px;
height: 300px;
}

This is a simple Cascading Stylesheet file, which is allocating 300px width and height to the paragraph tag present in index.html file. It’ll be helpful when we integrate Google Maps into our application( in the future videos ).

Javascript File
myScript.js

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
$(document).ready(function(){
 
if( navigator.geolocation )
 navigator.geolocation.getCurrentPosition(success);
else
 $("p").html("HTML5 Not Supported");
 
});
 
function success(position)
{
$("p").html("Latitude: "+position.coords.latitude+
            "<br />Longitude: "+position.coords.longitude+
"<br />Accuracy: "+position.coords.accuracy);
}

This is a minimalistic approach to using geolocation API. We’ll improve it in future videos.

Once the document is loaded and ready, we check if the browser supports Geolocation API.
We do that by checking if navigator.geolocation object exists.
If it doesn’t exist, we display appropriate message to the user(“HTML5 Not Supported”).

If it does support navigator.geolocation, we’ll make use of it’s methods and get the user location.
navigator.geolocation has 3 methods:
getCurrentPosition
watchPosition
clearWatch

In this video tutorial we’ll be looking at the first method, i.e., getCurrentPosition()

navigator.geolocation.getCurrentPosition(success, error, option);

getCurrentPosition()
It takes 3 parameters:
success handler
error handler
and options.

success handler is mandatory.
error handler and options are optional.

getCurrentPosition method passes the users current location information to the success handler, in the form of position object.

position object: success handler method

position object has two properies: coords and timestamp

coords(coordinates) inturn has 7 properties:
3 are supported by most browsers:
latitude
longitude
accuracy

..other 4 are not widely supported:
altitude
altitudeAccuracy
heading
speed

In this tutorial we’re using latitude, longitude and accuracy properties, as it’s supported by most browsers.

Geolocation API – Success Handler: HTML5


[youtube https://www.youtube.com/watch?v=a3-ekroQoHo]

YouTube Link: https://www.youtube.com/watch?v=a3-ekroQoHo [Watch the Video In Full Screen.]



Note:
1. Geolocation API returns latitude and longitude values in decimal number system.
2. It determines users location by using various factors like: IP Address, GPS, Cell phone triangulation, WiFi etc.
3. We can’t know or specify which method it has to use to determine the users location.
4. If you’re getting 404 or googleapi not found, [object][object] etc error messages, then reload your webpage after you restart your system and/or your WiFi modem.
Make sure your WiFi modem is ON: because it’s one of the way Geolocation API will fetch your location from.

Missing things:
Error handling.
Options, to configure maps output. etc
Showing the location of the user on a MAP.
Showing real time movement of the user on a MAP.
All these will be covered in future videos. Stay Subscribed. Share this video with your friends.

Find Position of Left most Vowel: JavaScript

Develop and demonstrate a xhtml file which uses javascript program to find the first occurrence or the left most vowel in the user entered string.
Input: A String.
Output: Position of the left most or first occurrence of the vowel in the user entered string.

Video Explaining The JavaScript Code:


[youtube https://www.youtube.com/watch?v=ni3diSb5Y40]

YouTube Link: https://www.youtube.com/watch?v=ni3diSb5Y40 [Watch the Video In Full Screen.]


Work Flow:
Step 1: Prompt the user to enter a string, store the user entered string in a variable called str.

Step 2: Convert the string in str to upper case using toUpperCase function. Now the original value of str is lost and its equivalent upper case string has been stored.
Ex: str = str.toUpperCase();

Step 3: Now find the length of the entered string using length function. i.e., variableName.length; Ex: str.length;

Step 4: Using for loop, loop through the string from 0 to the string length(which is calculated in Step 3).

Step 5: Using chatAt function fetch one character at a time from str and store it in variable chr. Ex: chr = str.charAt(i);

Step 6: Now compare the value in chr with upper case vowels: A, E, I, O, U.

Step 7: If chr matches any vowel then break out of for loop.

Step 8: If the value of i after coming out of the for loop, is less than string length then print the value of i which is the position of the left most occurrence of the vowel. If the value of i is greater than or equal to string length, then Vowel not found in the entered string.
Javascrip coding explained in above video:

 

 
Finding Left most Vowel in the Input String
 
 

Input/Output:
If Microsoft is the input string, then the position of the first occurrence of vowel is 2. i.e., i.
For Oracle, O is a vowel, so the position is 1.
For Technotip, e is the first vowel, so the position is 2.
For any input which do not have a vowel in it, the above javascript program outputs this statement: No vowel found in the entered string.