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.

Removing Documents: MongoDB

Lets learn how to remove documents from the collection using remove() and drop() methods.

remove drop mongodb

test database, names collection

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
> db.names.find().pretty()
{
        "_id" : ObjectId("53c6392a2eea8062e084cb57"),
        "Company" : "Google",
        "Product" : "Nexus",
        "No" : 1
}
{
        "_id" : ObjectId("53c639392eea8062e084cb58"),
        "Company" : "Apple",
        "Product" : "Mac",
        "No" : 2
}
{
        "_id" : ObjectId("53c63b26b003603dfdcf8c52"),
        "Company" : "Xiaomi",
        "Product" : "Mi3",
        "No" : 3
}
{
        "_id" : ObjectId("53c63bd1b003603dfdcf8c53"),
        "Product" : "Smart Watch",
        "No" : 4,
        "Company" : "Sony"
}

We have 4 documents in “names” collection.

remove() method, with simple condition

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
> db.names.remove({"No": 4});
WriteResult({ "nRemoved" : 1 })
 
> db.names.find().pretty()
{
        "_id" : ObjectId("53c6392a2eea8062e084cb57"),
        "Company" : "Google",
        "Product" : "Nexus",
        "No" : 1,
        "IT" : "true"
}
{
        "_id" : ObjectId("53c639392eea8062e084cb58"),
        "Company" : "Apple",
        "Product" : "Mac",
        "No" : 2,
        "IT" : "true"
}
{
        "_id" : ObjectId("53c63b26b003603dfdcf8c52"),
        "Company" : "Xiaomi",
        "Product" : "Mi3",
        "No" : 3,
        "IT" : "true"
}

Here the document with “No: 4” was removed from the collection.

Removing Documents: MongoDB


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

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



remove() method, with comparison condition

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
> db.names.remove({"No": {$gt: 2}});
WriteResult({ "nRemoved" : 1 })
 
> db.names.find().pretty()
{
        "_id" : ObjectId("53c6392a2eea8062e084cb57"),
        "Company" : "Google",
        "Product" : "Nexus",
        "No" : 1,
        "IT" : "true"
}
{
        "_id" : ObjectId("53c639392eea8062e084cb58"),
        "Company" : "Apple",
        "Product" : "Mac",
        "No" : 2,
        "IT" : "true"
}

Here whatever documents which has “No” greater than 2 got removed.

remove() method to remove all documents from the collection

1
2
3
4
5
6
7
8
9
10
11
> db.names.remove({});
WriteResult({ "nRemoved" : 2 })
 
> db.names.find().pretty()
 
> show collections
names
system.indexes
 
> db.system.indexes.find().pretty()
{ "v" : 1, "key" : { "_id" : 1 }, "name" : "_id_", "ns" : "test.names" }

If we pass empty argument to remove() method, it matches with all the documents present in the collection, hence removes all the documents one-by-one.

But it doesn’t remove the contents/documents/index present in “system.indexes” collection.

drop() method

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
> db.names.find()
 
> db.names.insert({"Company": "Apple", "Product": "iPhone", "No": 1});
WriteResult({ "nInserted" : 1 })
 
> db.names.insert({"Company": "Google", "Product": "Nexus", "No": 2});
WriteResult({ "nInserted" : 1 })
 
> db.names.find().pretty()
{
        "_id" : ObjectId("53c6c5d95879b1ff1f0b8356"),
        "Company" : "Apple",
        "Product" : "iPhone",
        "No" : 1
}
{
        "_id" : ObjectId("53c6392a2eea8062e084cb57"),
        "Company" : "Google",
        "Product" : "Nexus",
        "No" : 1,
        "IT" : "true"
}
 
> db.names.drop();
true
 
> db.names.find().pretty()
 
> db.system.indexes.find().pretty()

Since “names” collection was empty, we inserted 2 documents into it. Now we applied drop() method on the collection, which drops all the document present in the collections at once. It also removes the document/index/content present inside “system.indexes” collection.

Note: If you want to remove/drop all the documents present inside the collection, make use of drop() method, as it removes all the documents at once, its more efficient than remove({}) method which removes documents one by one. Use remove() method, when you want to remove one or a set of documents from the collection.

Remove / Delete Data From MongoDB: Node.js

Today lets learn how to delete documents from MongoDB collection via your node.js application.

remove-delete-data-mongoDB-nodejs

In this video tutorial, I’ll show you how to make use of normal app.get to delete data and also the use of app.delete to accomplish the same.

Related Read:
Connecting To MongoDB Using Mongoose: Node.js
Save data To MongoDB: Node.js
Fetch Data From MongoDB: Node.js
Fetch Individual User Data From MongoDB: Node.js
Update / Edit Data In MongoDB: Node.js
..please go through these tutorials before proceeding further. It’ll take less than 20 min

Adding Delete link
view/show.jade

1
2
3
4
5
6
7
8
<h1>#{user.name}</h1>
ul
 li Age: #{user.age}
 li Email: #{user._id}
 
ul
 li 
  a(href="/user/#{user._id}/delete") Delete

This adds Delete link below each individual user information.

Delete Routes: remove()
app.js

1
2
3
4
5
6
7
8
9
var user = mongoose.model('emp', Schema);
 
app.get('/user/:id/delete', function(req, res){
user.remove({_id: req.params.id}, 
   function(err){
if(err) res.json(err);
else    res.redirect('/view');
});
});

Here we simply make use of app.get and the route we are defining is /user/:id/delete Once the user clicks on the delete link with the user id in it, the route gets triggered and by using remove() method upon user object, we fetch the user data with the particular id that the user passed in from the URL and delete it from our mongoDB collection.

Delete Routes: findByIdAndRemove()
app.js

1
2
3
4
5
6
7
8
9
var user = mongoose.model('emp', Schema);
 
app.get('/user/:id/delete', function(req, res){
user.findByIdAndRemove({_id: req.params.id}, 
   function(err, docs){
if(err) res.json(err);
else    res.redirect('/view');
});
});

Here we are using findByIdAndRemove() method of mongoose module to find the requested user and delete the user document. Syntax is same as remove() method, only change is, findByIdAndRemove() method also returns result object to the callback method along with error object.

app.delete
view/show.jade

1
2
3
4
5
6
7
8
9
10
11
12
<h1>#{user.name}</h1>
ul
 li Age: #{user.age}
 li Email: #{user._id}
 
ul
 li 
  a(href="/user/#{user._id}/edit") Edit
 li
  form(action="/user/#{user._id}", method="POST")
   input(type="hidden", name="_method", value="DELETE")
   button(type="submit") Delete

Here we replace the delete link with a delete button. Here the action field value is /user/#{user._id} and the method used is POST. But we are also passing a hidden input field which overrides the method from POST to DELETE inside our node application.

Delete Routes: app.delete() and findByIdAndRemove()
app.js

1
2
3
4
5
6
7
8
9
var user = mongoose.model('emp', Schema);
 
app.delete('/user/:id', function(req, res){
user.findByIdAndRemove({_id: req.params.id}, 
   function(err, docs){
if(err) res.json(err);
else    res.redirect('/view');
});
});

The findByIdAndRemove() method works the same way as explained above.

Delete Routes: app.delete() and remove()
app.js

1
2
3
4
5
6
7
8
9
var user = mongoose.model('emp', Schema);
 
app.delete('/user/:id', function(req, res){
user.remove({_id: req.params.id}, 
   function(err){
if(err) res.json(err);
else    res.redirect('/view');
});
});

The remove() method works the same way as explained above.

Remove / Delete Data From MongoDB: Node.js


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

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



Full Source Code

new user registration form
public/index.html

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
< !DOCTYPE html>
<html>
<head>
<title>Registration Form</title>
</head>
<body>
 <form action="/new" method="POST">
<label for="email">Email: </label>
  <input type="email" name="email" /><br />
<label for="name">Name: </label>
  <input type="text" name="name" /><br />
<label for="age">Age: </label>
  <input type="number" name="age" /><br />
 <input type="submit"/>
</form>
</body>
</html>

Link to all registered users
view/index.jade

1
2
3
4
ul
each user in users
 li
  a(href='/user/#{user._id}') #{user.name}

Edit form
view/edit-form.jade

1
2
3
4
5
6
7
8
9
<h1>Editing #{user.name}'s profile!</h1>
form(method="POST", action="/user/#{user._id}")
 input(type="hidden", name="_method", value="PUT")
 p Name:
  input(type="text", name="name", value="#{user.name}")
 p Age:
  input(type="number", name="age", value="#{user.age}")
 p
  input(type="submit")

Show Individual User Information
view/show.jade

1
2
3
4
5
6
7
8
9
10
11
12
<h1>#{user.name}</h1>
ul
 li Age: #{user.age}
 li Email: #{user._id}
 
ul
 li 
  a(href="/user/#{user._id}/edit") Edit
 li
  form(action="/user/#{user._id}", method="POST")
   input(type="hidden", name="_method", value="DELETE")
   button(type="submit") Delete

Main Node.js Application File, with Create, Read, Update and Delete Routes
app.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
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
var express = require('express');
var http = require('http');
var path = require('path');
var mongoose = require('mongoose');
 
var app = express();
 
// all environments
app.set('port', process.env.PORT || 3000);
app.set('views', __dirname + '/views');
app.set('view engine', 'jade');
 
app.use(express.bodyParser());
app.use(express.methodOverride());
app.use(app.router);
app.use(express.static(path.join(__dirname, 'public')));
 
mongoose.connect('mongodb://localhost/Company');
 
var Schema = new mongoose.Schema({
_id    : String,
name: String,
age   : Number
});
 
var user = mongoose.model('emp', Schema);
 
app.delete('/user/:id', function(req, res){
user.findByIdAndRemove({_id: req.params.id}, 
   function(err, docs){
if(err) res.json(err);
else    res.redirect('/view');
});
});
 
app.get('/user/:id/edit', function(req, res){
res.render('edit-form', {user: req.userId});
});
 
app.put('/user/:id', function(req, res){
user.findByIdAndUpdate({_id: req.params.id},
                   {
     name: req.body.name,
  age   : req.body.age
   }, function(err, docs){
 if(err) res.json(err);
else
{ 
   console.log(docs);
   res.redirect('/user/'+req.params.id);
 }
 });
});
 
app.param('id', function(req, res, next, id){
user.findById(id, function(err, docs){
if(err) res.json(err);
else
{
req.userId = docs;
next();
}
});
});
 
 
app.get('/user/:id', function(req, res){
res.render('show', {user: req.userId});
});
 
app.get('/view', function(req, res){
user.find({}, function(err, docs){
if(err) res.json(err);
else    res.render('index', {users: docs})
});
});
 
app.post('/new', function(req, res){
new user({
_id    : req.body.email,
name: req.body.name,
age   : req.body.age
}).save(function(err, doc){
if(err) res.json(err);
else    res.redirect('/view');
});
});
 
 
var server = http.createServer(app).listen(app.get('port'), function(){
  console.log('Express server listening on port ' + app.get('port'));
});

Routes
/ for new entries
/view for viewing all the users
/user/:id to see individual user information
/user/:id/edit to edit individual user information

With these tutorials you can start building fully functional web application. But to make it more secure, incorporate sessions, validation and error handling.

External Module( NPM ) Install, Update, Remove: Node.js

This video tutorial illustrates searching, installing, updating and removing the external, free modules.

External Free Node Modules are listed at npmjs.org and is managed by NPMNode Package Manager.

There are so many amazing modules already written to handle so many sophisticated functionalities, that it becomes easy to use them in our application and build a robust, scalable application quickly.

Command to look at all the external module names and their respective description

1
npm search

It gives a long list of names and descriptions.

To make is look better, you can use GREP(if you’re on Linux or Unix based System)
Search with GREP

1
npm search | grep module_name

npm search followed by pipe symbol, which is followed by any module name.

For Windows users

1
npm search module_name

it gives all the details of available methods, properties and their description.

Installation of Modules

init command

1
npm init

Once you run this command, it prompts you with some optional things, like, name of the project, version, author, licensing etc. Once you’re done with that, it creates package.json file with all the details you provided.

The ‘init’ command in NPM allows us to identify our project and list out any Node Modules it requires.

Now open that package.json file: it looks somewhat like this
package.json file

1
2
3
4
5
6
7
8
9
10
11
12
{
  "name": "app",
  "version": "0.0.0",
  "description": "authentication application",
  "main": "index.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "repository": "",
  "author": "SATISH B",
  "license": "BSD"
}

You need to open this package.json file using a plain text editor and add your project dependencies i.e., some of the modules you need to install for your project.

In this video tutorial we’re installing 3 external modules:
express
jade
mongoose

package.json file, after editing

1
2
3
4
5
6
7
8
9
10
11
12
13
{
  "name": "app",
  "version": "0.0.0",
  "description": "authentication application",
  "main": "index.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
 "dependencies": { "express": "2.5.8", "jade": "0.26.1", "mongoose": "2.6.5" },
  "repository": "",
  "author": "SATISH B",
  "license": "BSD"
}

Now you’ve specified all the external modules your project depends on.

Now using install command, we need to install these modules.
installation command

1
npm install

Once this command is executed, it looks through the package.json file and installs all the dependency modules one by one.

External Module Install, Update, Remove via NPM: Node.js


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

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



What is a module?
A module is a self-contained series of one or more javascript files represented by an object.

Update Command

1
npm update

once you run this command, package.json file is parsed and the dependency modules are checked for any updates, if any, it’ll be updated.
If any module is installed with -g (global scope), i.e., the root installation, then while updating or removing them, it may throw some errors, in such case, use sudo keyword:

Update Command

1
sudo npm update -g

This would solve the problem both for updating and deleting external modules.

remove/delete module command

1
npm prune

To remove the unused modules: open package.json file and remove the module names which you want to remove. Save the package.json file and then run above(npm prune) command. This would safely remove the modules you no more intend to use in your project.

List Global module: using command

1
npm -g ls

This lists all the global modules, it’s path and file structure: as shown below:

Example output

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
C:\node\express_example>npm  -g ls
C:\Users\Satish\AppData\Roaming\npm
└─┬ [email protected]
  ├── [email protected]
  ├─┬ [email protected]
  │ └── [email protected]
  ├─┬ [email protected]
  │ ├── [email protected]
  │ ├─┬ [email protected]
  │ │ ├── [email protected]
  │ │ └── [email protected]
  │ ├── [email protected]
  │ ├── [email protected]
  │ └── [email protected]
  ├── [email protected]
  ├── [email protected]
  ├── [email protected]
  ├── [email protected]
  ├── [email protected]
  ├── [email protected]
  ├── [email protected]
  └─┬ [email protected]
    └── [email protected]

Removing/Uninstalling Global modules: using command

1
npm -g rm

This removes all the global modules installed.

Clear cache

1
npm cache clear

After modifiying things from command prompt, if it’s still not working, try clearing the cache.

Note:
To install latest version of the module: you’ll need to write * (asterisk or star) in the place of version number inside package.json file.

Working With Images: Small jQuery Application

In this video tutorial, we shall test our skills in jQuery: bind, unbind, append and remove functions. Also we shall see the use of chain methods.

jQuery Event Handling: Binding and Unbinding
Animate Image with ‘this’ Selector: jQuery
Append/Add and Remove HTML/XML Elements: jQuery

Assume that a client has mailed her requirements to us:
She has 5 images in her html page.
Once the user clicks on a image, a message should popin beside the image.
Image should be clickable only once.
Once the user clicks on other images, the messages appended beside previously clicked image must be removed.

With these requirements in mind, we shall start developing our image based jQuery Application.

HTML code
index.html

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
<html>
 <head><title>Working With Images: Small jQuery Application</title>
 <style type="text/css">
 img{
  padding: 10px;
 }
 </style>
 </head>
 <body>
 
   <div> <img src="images/aperture.png" width="69" height="69" /> </div>
   <div> <img src="images/coda.png" width="69" height="69" /> </div>
   <div> <img src="images/finder.png" width="69" height="69" /> </div>
   <div> <img src="images/photoshop.png" width="69" height="69" /> </div>
   <div> <img src="images/safari.png" width="69" height="69" /> </div>
 
   <script type="text/javascript" src="script/jquery-1.8.1.min.js"></script>
   <script type="text/javascript" src="script/my_script.js"></script>
 </body>
</html>

Here we have included 5 images and have added 10px padding using CSS.
Each image is being placed inside a div tag.

Note:
So img is a child of div or div is the parent of img.

jQuery code
my_script.js

1
2
3
4
5
6
7
8
9
$(document).ready( function() {
 
  $("img").click( function() {
   $("b").remove();
   $(this).parent().append("<b>You clicked on Me!</b>");
   $(this).unbind();
 });
 
});

Once the document is ready and the user clicks on a image:
1. Any b tag present in the document is removed. Thus, the message associated with the image which was being clicked previously is removed.
2. The parent tag of the image being clicked: i.e., div tag is selected and a message with b tag is appended to it, which appears beside the image being clicked by the user.
3. The event associated with the image being clicked is removed.

Note:
Use of function().function() is called chain method.
Example:
parent().append();
next().parent().remove(); etc

Make sure to maintain the order of the code. If you replace or rearrange the code in a way other than above, you wouldn’t get expected result.
While practicing, change the order of the code and look for the output, that would help you understand the code and the flow / execution flow well.

Video Tutorial: Working With Images: Small jQuery Application


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

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



Keep testing your jQuery skills by doing some mini projects like this one.
Let it be small, so that it doesn’t take forever to test your skills.

You could even test and enhance your jQuery skills by helping people on our forum.