Why do I get the following warning in console ? Everything seems to be working as expected but Angular complains. What would be a solution for this issue ?
StackBlitz is here
I know a possible solution is to communicate event via parent child communication instead of using service but that is not an option for me since this is an isolation of a problem in a larger code base.
Error Message
ERROR Error: ExpressionChangedAfterItHasBeenCheckedError: Expression has changed after it was checked. Previous value: 'ngIf: false'. Current value: 'ngIf: true'.
at viewDebugError (core.js:20439)
at expressionChangedAfterItHasBeenCheckedError (core.js:20427)
at checkBindingNoChanges (core.js:20529)
at checkNoChangesNodeInline (core.js:23400)
at checkNoChangesNode (core.js:23389)
at debugCheckNoChangesNode (core.js:23993)
at debugCheckDirectivesFn (core.js:23921)
at Object.eval [as updateDirectives] (AppComponent.html:6)
at Object.debugUpdateDirectives [as updateDirectives] (core.js:23910)
at checkNoChangesView (core.js:23288)
app.component.html
<div style="text-align:center">
<h1>
Welcome to {{ title }}!
</h1>
<h1 *ngIf="mainSectionContent?.buttontext?.length > 0">
Welcome to {{ title }}!
</h1>
<app-employee></app-employee>
</div>
AppComponent
export class AppComponent implements OnInit {
title = 'expression-changed';
mainSectionContent:MainSectionContent;
contentAnnounce$:Observable<MainSectionContent>;
constructor(private mainContentService:MaincontentService) { }
ngOnInit(): void {
this.contentAnnounce$ = this.mainContentService.contentAnnounce$;
this.contentAnnounce$.subscribe(mainSectionContent =>
{
this.mainSectionContent = mainSectionContent
}
);
}
}
EmployeeComponent
export class EmployeeComponent implements OnInit {
constructor(private mainSectionContentService:MaincontentService) { }
ngOnInit() {
this.mainSectionContentService.announceContent({
mainheading:'Employee Manger',
mainsubheading:'To manage PrivilegeManager Employees',
sectionheading:'Employee List',
buttontext:'Create Employee'
});
}
}
MaincontentService
@Injectable({
providedIn: 'root'
})
export class MaincontentService {
private contentAnnounce = new Subject<MainSectionContent>();
contentAnnounce$ = this.contentAnnounce.asObservable();
constructor() { }
announceContent(content:MainSectionContent){
this.contentAnnounce.next(content);
}
}
`
– ashish.gd Mar 22 '19 at 06:37