简体   繁体   中英

ERROR Error: ExpressionChangedAfterItHasBeenCheckedError: Expression has changed after it was checked

import { Component } from '@angular/core'; import { PeriodsService } from '../periods';

@Component({
    selector: 'app-control-panel',
    templateUrl: './control-panel.component.html',
    styleUrls: ['./control-panel.component.css'] 
}) 
export class ControlPanelComponent {
    private selectedPeriod;
    private selectedPosition;

    constructor(
        private periodsService: PeriodsService,
        private positionsService: PositionsService,
        private classifierService: ClassifierService
    ) {
        this.periodsService.periodChange.subscribe(period => {
            this.selectedPeriod = period;
        });
    }

    get periodTitle() {
        return this.selectedPeriod.p_display_name;
    }

    }


    //Template file: control-panel.component.html
    {{periodTitle}}

Blockquote

use ChangeDetectorRef :

import { Component, ChangeDetectorRef } from '@angular/core'; import { PeriodsService } from '../periods';

@Component({
    selector: 'app-control-panel',
    templateUrl: './control-panel.component.html',
    styleUrls: ['./control-panel.component.css'] 
}) 
export class ControlPanelComponent {
    private selectedPeriod;
    private selectedPosition;

    constructor(
        private periodsService: PeriodsService,
        private positionsService: PositionsService,
        private classifierService: ClassifierService,
        private cdRef: ChangeDetectorRef ,
    ) {

    }

    ngOnInit(){
        this.periodsService.periodChange.subscribe(period => {
            this.selectedPeriod = period;
            this.cdRef.detectChanges();
        });
    }
    get periodTitle() {
        return this.selectedPeriod.p_display_name;
    }

    }


    //Template file: control-panel.component.html
    {{periodTitle}}

ChangeDetectorRef.detectChanges() via sharing data between child & parent

import { Component,
     Input,
     ChangeDetectionStrategy,
     ChangeDetectorRef } from '@angular/core';

@Component({
  selector: 'app-child',
  templateUrl: './child.component.html',
  changeDetection: ChangeDetectionStrategy.OnPush
 })



export class ChildComponent {
@Input() data: string[];

constructor(private cd: ChangeDetectorRef) {}

    refresh() {
    this.cd.detectChanges();
   }
 }

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