[Fixed] Angular: Display nothing in DOM incase of Null

Issue

I am removing elements of an array if they match with elements of another array. I am getting an issue here, when I try to print this new modified array in HTML, it prints nothing for that particular index but, occupies the row. I want it not to occupy any row of select if the array has null/undefined values. How can I do that? I have tried few things, but couldn’t find any help.

Here’s the code:

TS

 for(var i = 0; i < this.subAdminData.length; i++)
    {
        for(var j = 0; j < this.subAdminAllData.length; j++)
        {
          if(this.subAdminData[i].roles == this.subAdminAllData[j])
          {
            delete this.subAdminAllData[j]; // this removes the element but when I try to print this 
                                            // array in HTML using *ngFor then it is printing empty
                                            // values for the deleted values meaning it's occupying a 
                                            // full row of select with nothing in it
          }
        }
    }

HTML

<div class="input-group">
      <div class="input-group-addon">
        <select class="custom-select" size = "5" name= "subadminrights" required style = "width: 100%;">
          <option selected disabled value = "Select admin rights">Select sub administrative rights: </option>
          <option value="full" *ngFor = "let saData of subAdminAllData">
            
            {{saData}}</option>
            <!-- occupies a row with nothing in it if the array index has null value -->

        </select>
      </div>
    </div>

Solution

As said in comment, you cannot use ‘delete’ for this but rather splice the item or other filtering. According to the code you provided the below filter should works.

    const filteredData = subAdminAllData.filter(data => !subAdminData.some((data2) => data2.roles === data));

With this code you should only keep subAdminAllData elements which are not a ‘roles’ property in your subAdminData array.

Leave a Reply

(*) Required, Your email will not be published