简体   繁体   中英

onPush change detection strategy not updating values in Angular

I'm learning how to use the onPush detection strategy. My view updates fine, but the variables on my child.component.ts values don't, but they do on the child.component.html

CHILD COMPONENT

@Component({
  ....
  changeDetection: ChangeDetectionStrategy.OnPush
})

export class BdayFormComponent implements OnInit {

  @Input() question: Question;
  @Output() nextQuestion = new EventEmitter<Question>();


  nextQuestions(): void {
    ...
    this.nextQuestion.emit(......)
    console.log(this.question);
  }
}

As you can see nextQuestion , tells the parent component to dispatch an action to get new question. I can see the next question on my HTML (let's say question #2), but when I do the console.log(this.questions); it prints the question #1.

PARENT COMPONENT

export class BdayShellComponent implements OnInit {
  question$: Observable<Question>;

  constructor(private store: Store<fromProduct.State>) { }

  ngOnInit(): void {
    this.question$ = this.store.pipe(select(fromProduct.getCurrentQuestion));
  }

  setCurrentQuestion(question: Question): void {
    this.store.dispatch(new bdayActions.SetCurrentQuestion(question));
  }
}

PARENT COMPONENT HTML

<app-bday-form [question]="question$ | async"
        (nextQuestion)="setCurrentQuestion($event)"></app-bday-form>

At the time when you put the log statement, the component didn't receive the new input.

Try the following, and you'll see the value being logged

  ngOnChanges(changes: SimpleChanges) {
    console.log(changes.question)
  }

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