As I delve into the world of Angular, I am faced with a challenge in creating a reusable component that will be bundled into an npm module. The issue lies in the UI change detection aspect.
In order for the component to function properly, the application first needs to make an API call to fetch the necessary data for setup, followed by some initialization steps within the component.
this.dataService.getData().subscribe((data) => {
this.data = data;
this.npmComponent.init(this.data);
});
<app-npm-component></app-npm-component>
Within my component, there are additional setup tasks that need to be executed initially and then it must continuously monitor changes in the data, rerun certain setup tasks, and update the UI accordingly.
@Component({
...,
changeDetection: ChangeDetectionStrategy.OnPush
});
...
init(setupData: any): void {
this.cdr.detectChanges();
this.data = setupData;
}
<ul *ngIf="data.arrayOfStuff">
<li *ngFor="let item of data.arrayOfStuff">{{item}}</li>
</ul>
The standard ChangeDetection implementation is throwing an error: NullInjectorError: No provider for ChangeDetectorRef! This occurs because the data is not being passed from the parent via the template.
What is the correct approach to handle such scenarios? Your insights are greatly appreciated.
Edit: I have discovered the solution using ViewChild.
@ViewChild(NpmComponent, {static: false}) npmComponent: NpmComponent;