Remove object from typescript array (Angular 2)

I'm just trying to remove an object from an array in typescript, in angular 2.4.0, let me show the code, its my html file:

button type="submit" (click)="addAnotherLanguague()" >Add non native languague</button>
<li *ngFor="let languague of listOfLanguagues;">
     <div class="form-item form-item--text">
           <label class="label invisible">Years studied</label>
           <input type="number" min="0" [(ngModel)]="languague.yearsStudied" name="years"  placeholder="Years studied"/>
     </div>
<button type="submit" (click)="removeLanguague(languague)" >Remove</button> // here you can see use of method
</li>

      

And there is component.ts

(...)
this.listOfLanguagues = new Array <LanguagueInformationData>();
    }
addAnotherLanguague(){
        this.listOfLanguagues.push(new LanguagueInformationData);
    }
    removeLanguague(languague){
        this.listOfLanguagues.slice(this.listOfLanguagues.indexOf(languague), 1);
    }
(...)

      

Adding works is good, but I tried everything to remove and still don't know how to transfer this link with language, I don't want to use .pop because I want to remove exactly that language, below which is the button. Can you help me?

[edit] I am having a problem with this code again because every time I try to add a new language (push) it clears my data from the classes existing in the array, do you know what might cause this?

+3


source to share


2 answers


<li *ngFor="let languague of listOfLanguagues; let i = index">

<button type="submit" (click)="removeLanguague(languague, i)" >Remove</button>



removeLanguague(languague, index){
    this.listOfLanguagues.splice(index, 1);
}

      

+7


source


You should use splice

, notslice

this.listOfLanguagues.splice(this.listOfLanguagues.indexOf(languague), 1);

      



slice

returns a section of an array, but splice

removes elements from the array and optionally inserts new elements in their place, returning the deleted elements

+3


source







All Articles