简体   繁体   English

角度2:在检查子组件属性后对其进行了更改

[英]Angular 2: Expression has changed after it was checked on accessing child component property

I have two tab components that I pass the same model data but filtered with a custom pipe: 我有两个选项卡组件,它们传递相同的模型数据,但使用自定义管道过滤:

<md-tab-group>
    <md-tab label="All ({{ allPeople.count }})">
        <tab-content #allPeople [content]="data"></tab-content>
    </md-tab>

    <md-tab label="Tennagers ({{ teenagers.count }})">
        <tab-content #teenagers [content]="data | filterByAge: 20"></tab-content>
    </md-tab>
</md-tab-group>

On the parent component, I want to access a property of a child. 在父组件上,我要访问子代的属性。 As you see I am doing that with ID connection: {{ allPeople.count }} 如您所见,我正在使用ID连接: {{ allPeople.count }}

On the child component, I have ngOnChanges() method that do some calculations and return the count property: 在子组件上,我具有ngOnChanges()方法,该方法进行一些计算并返回count属性:

ngOnChanges() {
    this.count = this.countPeople();
}

With this approach, it works but the following console error appears: 使用这种方法,它可以工作,但是会出现以下控制台错误:

Expression has changed after it was checked. 检查后表达式已更改。 Previous value: 'All (0)'. 先前值:“全部(0)”。 Current value: 'All (4)'. 当前值:“全部(4)”。

I know that it appears only in the development mode, but I also know that it is not a good practice. 我知道它仅出现在开发模式中,但是我也不知道这不是一个好习惯。 Is there another way that I can access the child property count when I have same changes on with. 当我进行相同的更改时,还有另一种方法可以访问子属性count

Here is a working example: https://plnkr.co/edit/YlKxh81ejJF7zofc4310?p=preview 这是一个工作示例: https : //plnkr.co/edit/YlKxh81ejJF7zofc4310?p=preview

You get this error when change detection causes changes to the mode. 当更改检测导致模式更改时,您会收到此错误。 Because ngOnChanges() is called by change detection, this is probably what causes the error in your case. 由于ngOnChanges()是由更改检测调用的,因此这可能是导致您的错误的原因。 You can work around be calling change detection explicitely after the update. 您可以解决在更新后显式调用更改检测的问题。

constructor(private cdRef:ChangeDetectorRef) {}

ngOnChanges() {
    setTimeout(() => this.count = this.countPeople());
    // this.cdRef.detectChanges();
}

I don't know why detectChanges() didn't work in your case, but setTimeout() did. 我不知道为什么detectChanges()在您的情况下不起作用,但是setTimeout()起作用了。 I assume it's related to other components depending on the change. 我认为它与其他组件有关,具体取决于更改。 detectChanges works only on the current component. detectChanges仅适用于当前组件。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM