简体   繁体   中英

Angular component property view not updating when function emits output event

Angular component variable is not updating in the view if the component method generates an output event. Variable in focus is 'qMode',

Function with generating output event (NOT UPDATING VARIABLE)

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,
        });
    }
}

Function without generating output event (UPDATING VARIABLE)

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

Please find here Code Demo ,

When you call emit on saveQuestion, this triggers the parent component to update the question list.

Since you don't have a track by value set, this re-renders the list. In the questions component onInit, the value is changed back to 'edit'.

You can fix this by adding a track by function to the list. This ensures that the components re-renders only when there is a change.

in app-component.html

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

in app-component.ts

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

You can find a stackblitz example here: https://stackblitz.com/edit/angular-fdshce

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM