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 ?
<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);
}
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With