我想从 *ngFor
中删除 *ngFor
中的项目。
当我删除回复“test2”时,
在我添加其他回复后,“test3”变为空。
<hello name="{{ name }}"></hello>
<form #form="ngForm" (ngSubmit)="submit()" ngNativeValidate class="mt-4">
<div *ngFor="let content of contents; let indexContent = index; let firstContent = first;">
<div *ngFor="let message of content.messages; let indexMessage = index; let firstMessage = first;">
<table>
<thead>
<tr>
<th>Id</th>
<th>Text</th>
<th class="text-right">Action</th>
</tr>
</thead>
<tbody>
<tr *ngFor="let reply of message.replies; let indexReply = index; let firstReply = first;">
<td [innerHtml]='reply.id'></td>
<td>
<input type="text"
id="{{indexContent}}-{{indexMessage}}-{{indexReply}}-reply-text"
[(ngModel)]=content.messages[indexMessage].replies[indexReply].text
name="[[indexContent]]-[{{indexMessage}}]-[{{indexReply}}]-reply-text">
<br>
<span [innerHtml]="contents[indexContent].messages[0].replies[indexReply].text"></span>
</td>
<td>
<span (click)="message.removeReply(reply)">Remove Reply</span>
</td>
</tr>
</tbody>
</table>
<br>
<span (click)="message.addNewReply()">
Add Reply
</span>
</div>
</div>
<br>
<button type="submit" class="btn btn-primary">Save</button>
</form>
我的消息模型具有添加回复、删除回复的不同功能
message.model.ts
import { Reply } from "./reply";
export class Message {
constructor(public id: number = 0,
public text: string = '',
public replies: any[] = []) {
}
public setModel(obj) {
Object.assign(this, obj);
}
addReply(new_reply) {
this.replies.push(new_reply);
}
addNewReply() {
let new_reply = new Reply();
this.replies.push(new_reply);
}
removeReply(reply) {
this.replies.splice(this.replies.indexOf(reply), 1);
}
}
我在这里重现了我的问题:Remove object from array in *ngFor
in Angular
最佳答案
我会使用 trackBy
选项来避免 unexpected situations
html
<tr *ngFor="let reply of message.replies; trackBy: trackByFn;
^^^^^^^^^^^^^^^^^^
app.component.ts
trackByFn(i: number) {
return i
}
关于javascript - 使用 Angular 从 *ngFor 中删除 *ngFor 中的项目,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47696165/