Angular *ngFor TrackBy Element 超过 2 级循环

发布于 2025-01-18 09:21:41 字数 570 浏览 3 评论 0原文

我的代码中有 2 个 *ngFor 循环,有点像这样:

<div *ngFor="let page of pages; trackBy: trackByPageId" class="page">
    <app-item-component *ngFor="let item of page; trackBy: trackByItemID"
                        [item]="item">
    </app-item-component>
</div>

现在项目可以从一个页面移动到另一个页面,并且我不希望应用程序项目组件在页面之间移动时重新初始化。

使用 Angular 的 trackBy 允许移动数组项目,而无需再次运行 ngOnDestroy 和 ngOnInit 的组件,但是一旦我使用 2 个嵌套循环并且项目从一个列表移动到另一个列表,这就不再起作用了。

例如,像这样移动数组中的项目:
页[0]项[0] ->页[1]项[0]
将导致项目组件重新初始化。

有办法解决这个问题吗?

I have 2 *ngFor loops in my code somewhat like this:

<div *ngFor="let page of pages; trackBy: trackByPageId" class="page">
    <app-item-component *ngFor="let item of page; trackBy: trackByItemID"
                        [item]="item">
    </app-item-component>
</div>

Now the items may be moved from one page to another and i do not want the app-item Component to re-initialize when i move it between pages.

Using angular's trackBy allows array items to be moved without the components running ngOnDestroy ang ngOnInit again, but as soon as im using 2 nested loops and an item moves from one list to another, this doesn't work anymore.

For Example, moving an item in the array like this:
pages[0]items[0] -> pages[1]items[0]
would cause the item component to re-initialize.

Is there a way to solve this?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

生寂 2025-01-25 09:21:41

您可以在.ts内部有1个输入属性

@Input() checker: boolean;  

,并在.html内使用它,

<div *ngFor="let page of pages; trackBy: trackByPageId" class="page">
   <ng-container ngIf="checker"> 
    <app-item-component *ngFor="let item of page; trackBy: trackByItemID"
                        [item]="item">
    </app-item-component>
   </ng-container>
</div>

以通过容器NGIF渲染。

You can have 1 Input property inside your .ts

@Input() checker: boolean;  

and use it inside .html

<div *ngFor="let page of pages; trackBy: trackByPageId" class="page">
   <ng-container ngIf="checker"> 
    <app-item-component *ngFor="let item of page; trackBy: trackByItemID"
                        [item]="item">
    </app-item-component>
   </ng-container>
</div>

This way it will render depending on the containers ngIf

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文