我正在尝试在 Angular 11(严格模式)中延迟加载组件 this guide 。严格模式一直很痛苦,因为几乎没有示例/教程使用它。
该组件将加载适当的 header 组件(最终)。我只是想为“站点 A”延迟加载一个来启动。
header 加载器组件.ts
@Component({
selector: 'header-loader',
template: `<ng-template [ngComponentOutlet]="headerComponent | async"></ng-template>`,
styles: []
})
export class HeaderLoaderComponent implements OnInit {
headerComponent: Promise<Type<SiteAHeaderComponent>>;
constructor() { }
ngOnInit(): void {
this.LoadHeaderComponent();
}
private LoadHeaderComponent() {
if (!this.headerComponent) {
this.headerComponent = import(`../myFolder/siteA-header/siteA-header.component`)
.then(({ SiteAHeaderComponent}) => SiteAHeaderComponent);
}
}
}
这样,我收到错误:
Property 'headerComponent' has no initializer and is not definitely assigned in the constructor.
好吧,我现在已经习惯了严格模式下的错误,所以我将其更改为:
headerComponent: Promise<Type<SiteAHeaderComponent>> | null = null;
因此它可以在 ngOnInit 有机会设置它之前启动 null。
现在在[ngComponentOutlet]
上我得到:
Type 'Type | null' is not assignable to type 'Type'
如何设置 headerComponent
的值?
编辑:
可以肯定的是,我只是在暂时禁用 Strict 的情况下尝试过此操作,效果很好。
最佳答案
在分配属性时使用 !
符号与属性,例如 headerComponent!
。
带有属性名称的 !
符号意味着您明确声明 - “我知道这个属性有一个非空值”。在你的情况下,如果它有一个非空值,那么它的值肯定是 Type
类型。
编辑:
由于属性 headerComponent
是 Promise
类型,因此您必须使用 !
符号将模板中的 async
管道括起来,如 (headerComponent|async)!
。
此外,我建议使用 -
headerComponent: Promise<Type<any>> | null = null;
否则,您稍后将无法通过 headerComponent
属性设置不同类型的 header 组件。
关于angular - 严格模式 - 将值设置为带有延迟加载组件的 ngComponentOutlet 时类型不兼容,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66341154/