Jér*_*lle 1 javascript typescript angular
我想在删除项目*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>
Run Code Online (Sandbox Code Playgroud)
和我的消息模型用不同的功能添加回复,删除回复
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);
}
}
Run Code Online (Sandbox Code Playgroud)
我在这里重现我的问题:从*ngForAngular中的数组中删除对象
我会使用trackBy选项来避免意外情况
HTML
<tr *ngFor="let reply of message.replies; trackBy: trackByFn;
^^^^^^^^^^^^^^^^^^
Run Code Online (Sandbox Code Playgroud)
app.component.ts
trackByFn(i: number) {
return i
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
3228 次 |
| 最近记录: |