I am attempting to implement lazy loading for a component in Angular 11 (strict mode) using guidance from this tutorial. Dealing with strict mode has been challenging as there are very few resources available that cater to it.
The goal is to have a component load the appropriate header component (eventually). For now, I am focused on lazily loading one for "site A".
header-loader-component.ts
@Component({
selector: 'header-loader',
template: `<ng-template [ngComponentOutlet]="headerComponent | async"></ng-template>`,
styles: []
})
export class HeaderLoaderComponent implements OnInit {
headerComponent: Promise<Type<SiteAHeaderComponent>> | null = null;
constructor() { }
ngOnInit(): void {
this.LoadHeaderComponent();
}
private LoadHeaderComponent() {
if (!this.headerComponent) {
this.headerComponent = import(`../myFolder/siteA-header/siteA-header.component`)
.then(({ SiteAHeaderComponent }) => SiteAHeaderComponent);
}
}
}
Upon implementation, I encountered the error:
Property 'headerComponent' has no initializer and is not definitely assigned in the constructor.
To address this, I initialized the variable like so:
headerComponent: Promise<Type<SiteAHeaderComponent>> | null = null;
This allows it to start as null before being set by ngOnInit.
However, when using [ngComponentOutlet]
, I faced another issue:
Type 'Type | null' is not assignable to type 'Type'
How can I correctly assign a value to headerComponent
?
Edit:
Just to confirm, I temporarily disabled Strict mode and the implementation worked perfectly.