我已经针对此问题进行了一些研究,但现在不确定执行中是否有错误或错误。
我有一个使用服务来获取一些数据的元素,然后将其传递给子元素,但是当我更新数据时,我遇到了错误。
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>
加载应用程序时,一切都很好,但是如果单击“计数”按钮,则会出现该错误。
答案 0 :(得分:0)
当您更改子组件中从父代传递的数据时,总是会发生该错误。您应该
1)不这样做
2)修改数据时使用changeDetectorRef.detectChanges()
。