Html 从数组打字稿中删除对象(Angular 2)
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/45056629/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Remove object from array typescript(Angular 2)
提问by J?drek Markowski
I just try to delete object from array in typescript, in angular 2.4.0, let me show the code, its my html file:
我只是尝试从打字稿中的数组中删除对象,在 angular 2.4.0 中,让我展示代码,它是我的 html 文件:
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
还有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?
添加效果很好,但我尝试了所有删除的方法,但仍然不知道如何传输该语言的引用,我不想使用 .pop,因为我想完全删除按钮下方的这个语言。你能帮助我吗?
[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 ?
[编辑] 此代码再次出现问题,因为每次我尝试添加新语言(推送)时,它都会清除数组中现有类的数据,您知道是什么原因导致的吗?
回答by elzoy
<li *ngFor="let languague of listOfLanguagues; let i = index">
<li *ngFor="let languague of listOfLanguagues; let i = index">
<button type="submit" (click)="removeLanguague(languague, i)" >Remove</button>
<button type="submit" (click)="removeLanguague(languague, i)" >Remove</button>
removeLanguague(languague, index){
this.listOfLanguagues.splice(index, 1);
}
回答by Poul Kruijt
You have to use splice
and not slice
你必须使用splice
而不是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
slice
返回数组的一部分,并splice
从数组中删除元素,如有必要,在它们的位置插入新元素,返回删除的元素