gpt4 book ai didi

javascript - 使用 Angular 从 *ngFor 中删除 *ngFor 中的项目

转载 作者:搜寻专家 更新时间:2023-10-30 22:05:17 27 4
gpt4 key购买 nike

我想从 *ngFor 中删除 *ngFor 中的项目。

enter image description here

当我删除回复“test2”时,

enter image description here

在我添加其他回复后,“test3”变为空。

enter image description here

<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

https://stackblitz.com/edit/angular-clmi7d

最佳答案

我会使用 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/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com