Search code examples
angularangular2-changedetection

How do I use static field for function in change detection cycle in Angular?


I want to use a static field instead of calling the function isCorrect(option.correct, i) on every CD cycle in my template. Please can you help me to do this. Thank you.

My template's code looks like this:

<form [formGroup]="formGroup">
  <ol *ngIf="!multipleAnswer">
    <div class="options" *ngFor="let option of currentQuestion.options; index as i">
      <mat-radio-button
        (change)="setSelected(i)"
        [class.is-correct]="option.selected && option.correct"
        [class.is-incorrect]="option.selected && !option.correct">

        <li>{{ option.text }}</li>

        <mat-icon class="feedback-icon" *ngIf="option.selected && option.correct && isCorrect(option.correct, i)">done
        </mat-icon>
        <mat-icon class="feedback-icon" *ngIf="option.selected && !option.correct">clear</mat-icon>
      </mat-radio-button>

      <section class="messages" *ngIf="option.selected">
        <div *ngIf="option.selected && option.correct && isCorrect(option.correct, i)">
          <mat-icon class="sentiment">sentiment_very_satisfied</mat-icon>&nbsp;&nbsp;&nbsp;
            <span class="message correct-message">
              You&apos;re right! {{ correctMessage }}
            </span>
        </div>
...

Solution

  • From what I understand, it's not really a static field that you need. You just need a variable on your component, or one of the options, to know if that option is correct.

    From the code you provided in your comment, I think your ìsCorrect method will always return true, so you can directly use option.correct instead of isCorrect(option.correct, i)

    If that isCorrect method really does some tricky logic, you can call that method in your setSelected method, which is called whenever the selection changes. Or you can set a component variable and use it in the template

    class MyComponent
    {
        public correct: isCorrectAnswerSelected = false;
        //...
        setSelected()
        {
         this.isCorrectAnswerSelected = this.isCorrect(... );
    

    template

    <div *ngIf="option.selected && option.correct && isCorrectAnswerSelected">