Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Remove object from array typescript(Angular 2)

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 ?

like image 756
Jędrek Markowski Avatar asked Jul 12 '17 11:07

Jędrek Markowski


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);
}
like image 54
elzoy Avatar answered Oct 09 '22 22:10

elzoy


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

like image 35
Poul Kruijt Avatar answered Oct 09 '22 23:10

Poul Kruijt