Remove object from array typescript(Angular 2)

Jędrek Markowski picture Jędrek Markowski · Jul 12, 2017 · Viewed 41.3k times · Source

I just try to delete object from 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 well, but I tried everything to remove and still dont know how to transfer that languague's reference, I dont want to use .pop, because I want to remove exactly this languague below which is button. Can you help me?

[edit] I got problem again with this code, because every time I try to add new languague(push) it clears my data on classes existing in array, do you know what can cause it ?

Answer

elzoy picture elzoy · Jul 12, 2017

<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);
}