Angular 2 *ngFor 处理更新错误

Angular 2 *ngFor handles update wrong

我有以下问题: 我正在使用这个 *ngFor 循环:

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

如果数组 "subsectors" 如下所示:

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"-Components 被添加到 "app-sector"-Component 中。 parent 通过我的 "app-component".

中的“@Input”从他的 parent 获取他的子部门

这是 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 不会创建新的组件,只会销毁一些组件。我真的看不出一个模式。它似乎是随机决定是销毁还是创建新组件。

这是我到目前为止尝试过的方法: 使用跟踪。我添加了一个返回 "id" 属性 的 trackBy 过滤器,但它没有改变任何东西。方法如下:

<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-sector> 在它的主体中包含另一个 <app-sector> 这让我假设你已经在你的 app-sector.[=20= 的模板中的某个地方使用了 ng-content ]

我在过去用 *ngForng-content 得到过类似的意外结果。

我通常在谷歌搜索这个主题时遇到

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 次,但这只是我的两分钱。希望对你有帮助。

我已经解决了这个问题。我不得不在 @Component({}) 中添加 changeDetection: ChangeDetectionStrategy.OnPush。它告诉 Angular2 将任何输入视为不可变的。 - 已解决。