Bill Noble Bill Noble - 4 months ago 21x
Javascript Question

Remove ionic 2 ion-card div using Javascript in controller

I need to remove an ionic 2 card when someone clicks on the trash icon. The code I have so far gives a

querySelector is null
error when I run it.

The view html looks like this:

<ion-card *ngFor="#mediaItem of mediaItems" id="item{{}}" class="media-item">

<ion-card-header class="title-header">
<div class="title-item">
<ion-icon name="trash" class="bookmark_trash_icon" (click)="removeItem("></ion-icon>

<ion-card-content class="outer-content" >

<img src='{{mediaItem.url}}'>


<ion-item class="bookmark-media-item">
<!-- <button (click)="topup(mediaItem)" clear item-left> -->

<div style="float:left;">
<ion-icon name="heart"></ion-icon>
{{mediaItem.liked}} &nbsp;
<ion-icon name="close-circle"></ion-icon>
{{mediaItem.disliked}} &nbsp;
<a (click)="showUserProfile(mediaItem.owner, mediaItem.username)" style="float:left;">
<div style="float:right;">
<img src="img/tiny-v.png" class="bookmark-v-icon">



My controller javascript code looks like this:

removeItem(theItemID) {
let cardToHide = '#item'+theItemID;
document.querySelector(cardToHide).style.display = 'none';

The error I get is

querySelector is null


You can send the object instead of the id by changing that part of the code:


And then find that object in you mediaItems array and delete it from there. Then your view will be automatically updated.

First get the index of that object in the array, and then you can use the mediaItems.splice(index, 1) to delete it from the array:

removeItem(theItem) {
    let index = this.mediaItems.indexOf(theItem);