I have an angular component which has a boolean variable "BodyToggle". In the component.ts file, I set it to true on a click event, and when the variable is set to true, I have an ngIf condition which triggers a modal.
component.ts
import {Component, EventEmitter, Output, Input, ViewEncapsulation, Injectable, AfterViewInit, OnInit, OnChanges, SimpleChange} from '@angular/core';
@Component({
selector: 'app-chart1',
templateUrl: `./chart1.component.html`
, encapsulation: ViewEncapsulation.None
})
@Injectable({
providedIn: 'root'
})
export class ChartComponent implements OnInit {
BodyToggle: boolean = false;
getCharts(){
let currentContext = this;
if (item.displayType === "bar") {
....
....
events: {
click: function(){
//show modal
currentContext.BodyToggle = true;
}
}
}
}
component.html
<div id="container">
<div *ngIf="BodyToggle">
<clr-modal [(clrModalOpen)]="BodyToggle" [clrModalSize]="'lg'">
<div class="modal-body">
...
</div>
</clr-modal>
</div>
</div>
Now, when I first render the modal, when I trigger the click event, the BodyToggle variable is set to true, but it is not reflected in the view (HTML). When I refresh the page, at the click event, I see the change to the variable BodyToggle reflected in the view. I dont understand why it does not reflect when I render the component for the first time. I also tried to use a setTimeOut to the set the value to true.
let currentContext = this;
click: function() {
//show modal
currentContext.BodyToggle = false;
setTimeout(() => {
currentContext.BodyToggle = true;
});
This also doesnt seem to solve the issue. Using ChangeDetectorRef throws a "provider not found" error, as this component is a child component to another parent component. Could you please help me how to implement this so that when the component is first rendered, a change to the variable BodyToggle should reflect in the view (HTML). (Basically looking for an implementation similar to scope.apply in angular)
EDIT
I did try ChangeDetectorRef.detectChanges(), but I was getting a provider not found error.
core.js:6014 ERROR Error: Uncaught (in promise): NullInjectorError: StaticInjectorError(AppModule)[ExpandableOompaLoompa -> ChangeDetectorRef]:
StaticInjectorError(Platform: core)[ExpandableOompaLoompa -> ChangeDetectorRef]:
NullInjectorError: No provider for ChangeDetectorRef!
NullInjectorError: StaticInjectorError(AppModule)[ExpandableOompaLoompa -> ChangeDetectorRef]:
StaticInjectorError(Platform: core)[ExpandableOompaLoompa -> ChangeDetectorRef]:
NullInjectorError: No provider for ChangeDetectorRef!
This is how I did implemented it in the component.ts file.
constructor(private crd: ChangeDetectorRef) {}
.....
events: {
click: function(){
//show modal
currentContext.BodyToggle = true;
cdr.detectChanges();
}
}
I also tried ApplicationRef.tick(), that did not work at all. Could you help me with why this error might have been occuring? Thanks