Here is the stackblitz code, where I am emitting event from child component when the API call is made using the service.ts
file.
My child.comp.ts
import { Component, Output,EventEmitter } from '@angular/core';
import {Service} from './service';
@Component({
selector: 'child',
template: `Child data: {{data}}`
})
export class ChildComponent {
@Output() change = new EventEmitter();
data: string;
constructor(private svc: Service){}
ngOnInit(){
this.change.emit(true);
this.svc.getMsg()
.subscribe( data =>{
this.data = data;
this.change.emit(false);
})
}
}
My app.comp.ts
import { Component ,ChangeDetectorRef} from '@angular/core';
import {Service} from './service';
@Component({
selector: 'my-app',
templateUrl: './app.component.html',
styleUrls: [ './app.component.css' ]
})
export class AppComponent {
name = 'Angular 6';
show= false;
constructor(svc: Service,private crd: ChangeDetectorRef){}
showData(event){
this.show = event;
// this.crd.detectChanges(); // this stops the error
}
}
As you can see that adding this.crd.detectChanges();
stops the error by letting angular
know that this is part which requires another change detection.
But, I came across this answer on SO where this error basically represents BAD design. and using detectChanges()
seems more like a fix as I have to write it explicitly.
Can someone help me with the GOOD design where I don't have to write it explicitly detectChanges()
at the places where the values will change in lifecycles.