嵌套的Angular元素抛出ExpressionChangedAfterItHaHasBeenCheckedError

时间:2018-12-05 15:03:04

标签: angular angular-elements

我已经针对此问题进行了一些研究,但现在不确定执行中是否有错误或错误。

我有一个使用服务来获取一些数据的元素,然后将其传递给子元素,但是当我更新数据时,我遇到了错误。

父元素

import { Component, OnInit, ViewEncapsulation} from '@angular/core';
import { TestService } from '../services/test.service';

@Component({
    selector: 'dm-element-with-service-test',
    templateUrl: './element-with-service-test.component.html',
    encapsulation: ViewEncapsulation.Emulated
})
export class ElementWithServiceTestComponent implements OnInit {
currentCount: number;

constructor(private testService: TestService) { }

    ngOnInit() {
        this.testService.count.subscribe(count => this.currentCount = count); 
    }

    count() {
        this.testService.addCount();
    }

}

父元素视图

<div>
    <button (click)="count()">count</button>
    <element-test [myNumber]="currentCount"></element-test>
</div>

子元素

import { Component, OnInit, ViewEncapsulation, Input } from '@angular/core';

@Component({
    selector: 'dm-element-test',
    templateUrl: './element-test.component.html',
    encapsulation: ViewEncapsulation.Emulated
})
export class ElementTestComponent implements OnInit {
    @Input() myNumber: number;
    constructor() { }

    ngOnInit() {
    // do stuff...
    }
}

子元素视图

<p>
    current number in this component: {{myNumber}}
</p>

应用程序模块

import { BrowserModule } from '@angular/platform-browser';
import { NgModule, Injector, CUSTOM_ELEMENTS_SCHEMA } from '@angular/core';
import { AppComponent } from './app.component';
import { ElementTestComponent } from './element-test/element-test.component';
import { createCustomElement } from '@angular/elements';
import { ElementWithServiceTestComponent } from './element-with-service-test/element-with-service-test.component';


@NgModule({
    declarations: [
        AppComponent,
        ElementTestComponent,
        ElementWithServiceTestComponent
    ],
    imports: [
        BrowserModule
    ],
    providers: [],
    schemas: [CUSTOM_ELEMENTS_SCHEMA ],
    entryComponents: [ElementTestComponent, ElementWithServiceTestComponent]
})
export class AppModule {
    constructor(private injector: Injector) {
        const el = createCustomElement(ElementTestComponent, { injector });
        const el2 = createCustomElement(ElementWithServiceTestComponent, { injector });
        customElements.define('element-test', el);
        customElements.define('element-with-service-test', el2);
    }
    ngDoBootstrap() { }
}

索引

<div class="tests">
     <element-with-service-test></element-with-service-test>
</div>

加载应用程序时,一切都很好,但是如果单击“计数”按钮,则会出现该错误。

1 个答案:

答案 0 :(得分:0)

当您更改子组件中从父代传递的数据时,总是会发生该错误。您应该

1)不这样做

2)修改数据时使用changeDetectorRef.detectChanges()

https://blog.angularindepth.com/everything-you-need-to-know-about-the-expressionchangedafterithasbeencheckederror-error-e3fd9ce7dbb4