我想从*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);
}
}
我在这里重现我的问题:从Angular中的*ngFor
中的数组中删除对象
答案 0 :(得分:5)
我会使用trackBy
选项来避免unexpected situations
<强> HTML 强>
<tr *ngFor="let reply of message.replies; trackBy: trackByFn;
^^^^^^^^^^^^^^^^^^
<强> app.component.ts 强>
trackByFn(i: number) {
return i
}
答案 1 :(得分:1)
您需要的是独立的ng-model选项。另外,我会简化ngModel
和innerHtml
绑定
<input type="text"
id="{{indexMessage}}-{{indexReply}}-reply-text"
[(ngModel)]="reply.text"
[ngModelOptions]="{standalone: true}"
name="{{indexMessage}}-{{indexReply}}-reply-text" />
<span [innerHtml]="reply.text"></span>
另一种选择是使用ngFor
trackBy
,因为@yurzui是suggested,在这种情况下不需要独立。
Reply.id
也存在问题。作为临时解决方法,您可以尝试以下方法:
let maxId = 0;
export class Reply {
constructor(public id: number = 0, public text: string = '') {
this.id = this.id || ++maxId;
}
}