Contacts Deleted!

Is there anything worse than having to delete a whole bunch of items from a website on an individual basis?  Click delete, ‘are you sure?’ confirmation, actual deletion, repeat over and over.  No one should have to do that.

Luckily, it’s fairly easy to allow for multiple deletes using simple checkboxes and Javascript.  We wanted to include this in our new Angular 2-driven contact management system.  We started by creating a deleteList array in the main component class for the contact list.  Then, on the form html template, we added a column for ‘Delete?’ with a checkbox in each row.  That checkbox gets a few important attributes: the name and id are both set to {{}} – this is the primary key for that contact in the database.  The ngModel is two-way bound to a contact.selected variable (which is initialized on the component class), and the change event is given a horribly named function: addRemove($

Back to the component class- we need a main delete function and a helper function.  The helper is very simple- it gets the target (passed in as $, and checks to see if we are checking or unchecking the box.  If checking, we add it to the deleteList array.  If unchecking, we remove that id from the array:

addRemove(target) {
    if(target.checked) {
    } else {
        this.deleteList.splice(this.deleteList.indexOf(myTarget), 1);

Then, we need the function to do the actual deletion.  It’s going to use a few pre-defined services (do we still call them that in A2?) to communicate with the backend and delete, as well as show a loader and notification of success/failure:

deleteContacts() {;
    this._contactService.modifyData(this.deleteList, '/contactdeletemultiple')
            response => {
            error => {
    this.deleteList = [];

This event is attached to a ‘Delete’ button on the html template. We added a little [hidden] attribute to only show that button if at least one box is checked.  Note that at the end of the function, we also reset the deleteList array to avoid passing in ids for items that were already deleted.

It seems to work great.  Quick and easy, as soon as we played with $event a bit.  Next week, we’ll jump back to Angular v1.5 a bit for an important lesson in order of operations- aka: Why I spent multiple hours unable to reset a simple form.


Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s