Remove object from array typescript(Angular 2)
Asked Answered
D

2

7

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 ?

Differentiation answered 12/7, 2017 at 11:37 Comment(2)
Possible duplicate of remove item from stored array in angular 2Flaming
I edited a little bit my question, cause of new issueMasseter
P
21

<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);
}
Proptosis answered 12/7, 2017 at 11:40 Comment(2)
why pass the language parameter if not using it?Katlynkatmai
@Ricardo Gellman IMO language object will require when you make a service call to delete language from database as well.Laodicea
F
13

You have to use splice and not slice

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

slice returns a section of an array, and splice removes elements from an array and, if necessary, inserts new elements in their place, returning the deleted elements

Flaming answered 12/7, 2017 at 11:41 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.