unsafePtr
unsafePtr

Reputation: 1763

Two-way data binding with nested ngFor

I have a proper answer component and i can use it this way

[(answer)]="answer"

It is all okey with fire event and it does work. The Question object contains the Anser[]. And when i try to use it:

<answer *ngFor="let answer of question.Answers" [(answer)]="answer"></answer>

I receive exception

Cannot assign to a reference or variable! ; Zone: ; Task: Promise.then ; Value: Error: Cannot assign to a reference or variable!(…) Error: Cannot assign to a reference or variable!

Anyone have an idea why is throw exception.

answer.component.ts

@Component({
    moduleId: module.id,
    selector: 'answer',
    templateUrl: 'answer.component.html',
})
export class AnswerComponent extends ComponentBase implements OnInit {
    @Input() answer: Answer;
    @Output() answerChange: EventEmitter<Answer> = new EventEmitter<Answer>();

    private _isToggled: boolean;
    @Input() set isToggled(value: boolean) {
        this._isToggled = (value === undefined) ? false : value;  
    }

    get isToggled() {
        return this._isToggled;
    }

    constructor() {
        super();
    }

    ngOnInit() {
        this.requestMaterialDesignUpdate();
    }


    toggle() {
        this.isToggled = !this.isToggled;
        this.requestMaterialDesignUpdate();
    }

    answerTextChanged(input: any) {
        this.answerChange.emit(this.answer);

    }

    markAnswerAsCorrect(event: Event) {
        this.answer.IsCorrect = !this.answer.IsCorrect;
        this.answerChange.emit(this.answer);
    }
}

answer.component.html

<div class="display-flex-nowrap textbookDetailsContainer">
    <div class="padding-2rem answerBorderLeft cursor-pointer width100">
        <header (click)="toggle()" class="answerRowOrder">
            <div>
                <i *ngIf="!isToggled" class="material-icons">arrow_drop_down</i>
                <i *ngIf="isToggled" class="material-icons">arrow_drop_up</i>
            </div>
            <span class="part-text" [innerHTML]="answer.Text"></span>
        </header>
        <div *ngIf="isToggled" class="padding-2rem">
            <ckeditor rows="3" [(ngModel)]="answer.Text" (change)="answerTextChanged($event)" name="answer" [config]="{ extraPlugins: 'justify,image2,divarea',  removePlugins: 'about'}"></ckeditor>
        </div>
    </div>
    <div class="padding-2rem answerBorderRight checkboxBigSize">
        <label class="mdl-checkbox mdl-js-checkbox mdl-js-ripple-effect float-left">
            <input type="checkbox" class="mdl-checkbox__input" [checked]="answer.IsCorrect" (change)="markAnswerAsCorrect($event)">
        </label>
    </div>
</div>

Upvotes: 3

Views: 4484

Answers (1)

G&#252;nter Z&#246;chbauer
G&#252;nter Z&#246;chbauer

Reputation: 657078

This might work

<answer *ngFor="let answer of question.Answers let idx=index"
    [(answer)]="question.Answers[idx]"></answer>

Upvotes: 5

Related Questions