加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 综合聚焦 > 服务器 > 安全 > 正文

Angular 2 * ngFor处理更新错误

发布时间:2020-12-17 16:59:59 所属栏目:安全 来源:网络整理
导读:我有以下问题: 我正在使用这个* ngFor循环: app-sector *ngFor="let subsector of sector.subsectors" [sector]="subsector"/app-sector 如果数组“子部门”看起来像这样: var subsectors = [ {text: 'test',title: 'test',id: 'abc'},{text: 'test123',t
我有以下问题:
我正在使用这个* ngFor循环:

<app-sector *ngFor="let subsector of sector.subsectors" [sector]="subsector"></app-sector>

如果数组“子部门”看起来像这样:

var subsectors = [
    {text: 'test',title: 'test',id: 'abc'},{text: 'test123',title: 'test123',id: 'def'},{text: 'test321',title: 'test321',id: 'ghi'}
]

它按预期增加了3个“app-sector”组件.那些“app-sector” – 组件被添加到“app-sector”组件中.父母通过我的“app-component”中的“@Input”从父母那里获取他的子部门.

这就是HTML-Structure的样子:

<app-root>
    <app-sector *ngIf="playlist" [sector]="playlist">
        <app-sector *ngFor="let subsector of sector.subsectors" [sector]="subsector"></app-sector>
    </app-sector>
</app-root>

现在问题出现在这里:
当我像这样更新子部门时:

//Add new subsectors
this.subsectors.push({text: 'Blah',title: 'Blah',id: '123'});
this.subsectors.push({text: 'Blah123',title: 'Blah123',id: '456'});
this.subsectors.push({text: 'Blah321',title: 'Blah321',id: '789'});

//Remove old subsectors
this.subsectors.splice(2,1);
this.subsectors.splice(1,1);
this.subsectors.splice(0,1);

* ngFor不会创建新的组件,只会破坏一些组件.我真的看不到一个模式.它似乎随机决定它是否会破坏或创建新的组件.

这是我尝试过的方法:
使用trackBy.我添加了一个trackBy过滤器,它返回了“id”属性但它没有改变任何东西.方法如下:

<app-sector *ngFor="let subsector of sector.subsectors; trackBy:identify;" [sector]="subsector"></app-sector>

identify(index,item){
    return item.id;
}

然后我尝试了一些我在研究这个问题时看到的技巧,比如使用切片而不是拼接.或者在Parent中我尝试这样做:

ngOnChanges(changes) {
    if(this.sector['subsectors']) {
        setTimeout(() => {
            console.log('spliced subsectores for reinitialization');
            this.sector['subsectors'] = this.sector['subsectors'].slice();
        },1000);
    }
}

我希望你能帮帮我!如果您需要任何进一步的信息,请在评论中询问我:)

亲切的问候.

解决方法

这只是我的两美分,但我觉得这是一个由 translcusion引起的问题

这是什么意思?

在模板中,您具有以下结构:

<app-root>
    <app-sector *ngIf="playlist" [sector]="playlist">
        <app-sector *ngFor="let subsector of sector.subsectors" [sector]="subsector"></app-sector>
    </app-sector>
</app-root>

< APP-扇区GT;在其体内包含另一个< app-sector>这让我假设你已经在app-sector的模板中使用了ng-content somwhere.

过去我使用* ngFor和ng-content获得了类似的意外结果.

在搜索主题时,我经常遇到this answer.

Children passed by the parent can only projected once (no matter how
many are there. If the elements don’t select
specific and different parts of the passed children using the select
attribute,then everything is projected to the first with
the default selector (none).

这不能解释为什么你的初始数据显示3次,但它只是我的两分钱.希望它可以提供帮助.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读