0

如果组件方法生成输出事件,则 Angular 组件变量不会在视图中更新。焦点变量是'qMode',

生成输出事件的函数(不更新变量)

save() {
    if (this.questionForm.valid) {
        this.question.type = this.questionForm.value.type;
        this.question.description = this.questionForm.value.description;

        this.qMode = 'view';

        this.saveQuestion.emit({
            index: this.index,
            question: this.questionForm.value,
        });
    }
}

不生成输出事件的函数(更新变量)

save() {
    if (this.questionForm.valid) {
        this.question.type = this.questionForm.value.type;
        this.question.description = this.questionForm.value.description;
        this.qMode = 'view';
    }
}

请在这里找到代码演示

4

1 回答 1

1

当您在 saveQuestion 上调用 emit 时,这会触发父组件更新问题列表。

由于您没有按值设置跟踪,因此会重新呈现列表。在问题组件 onInit 中,该值更改回“编辑”。

您可以通过在列表中添加按功能跟踪来解决此问题。这确保了组件仅在发生更改时重新渲染。

在 app-component.html 中

<div *ngFor="let question of questions; let i = index; trackBy: trackQuestion">

在 app-component.ts 中

trackQuestion(index: number, question) {
    return index.toString();
    // you can implement custom logic here using the question
}

您可以在此处找到 stackblitz 示例:https ://stackblitz.com/edit/angular-fdshce

于 2018-08-29T05:00:10.613 回答