错误:ExpressionChangedAfterItHasBeenCheckedError:表达式在检查后发生了变化

时间:2017-11-27 10:17:52

标签: angular angular-components

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}}
  

块引用

2 个答案:

答案 0 :(得分:2)

使用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}}

答案 1 :(得分:0)

ChangeDetectorRef.detectChanges()通过在子级与父级之间共享数据

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